Browse files

Add a MODELS.Playlist.diff method that does a coarse comparison of fi…

…elds.
  • Loading branch information...
1 parent c834c0c commit 9e75a2d4de850c8206d7e39368c33bd1b2503580 @jwheare committed Dec 18, 2009
Showing with 55 additions and 4 deletions.
  1. +15 −4 src/js/controllers/playlist.controller.js
  2. +40 −0 src/js/models/playlist.model.js
View
19 src/js/controllers/playlist.controller.js
@@ -488,14 +488,25 @@ Playlist.prototype = {
return;
}
var sub = playlist.subscription;
+ // Make a copy of the args so we don't modify the original
+ var args = sub.arguments.slice();
// Add callback and exception handler to the arguments
- sub.arguments.push(function callback (newPlaylist) {
+ args.push(function callback (newPlaylist) {
// compare with saved playlist and update/warn for conflicts?
+ var diffs = 0;
+ for (var field in playlist.diff(newPlaylist)) {
+ diffs++;
+ console.info(playlist[field], newPlaylist[field]);
+ }
+ if (!diffs) {
+ console.info('no updates');
+ }
});
- sub.arguments.push(function exceptionHandler (exception) {
- // show a warning icon and message
+ args.push(function exceptionHandler (exception) {
+ // show a warning icon and message?
+ exception.diagnose();
});
- IMPORTERS[sub.namespace][sub.method].apply(this, sub.arguments);
+ IMPORTERS[sub.namespace][sub.method].apply(this, args);
},
/* UNLOAD */
View
40 src/js/models/playlist.model.js
@@ -315,6 +315,8 @@ Playlist.prototype = {
return doc_ref;
},
get_doc: function () {
+ // Load tracks
+ this.load();
var doc = $.extend(this.get_doc_ref(), {
date: this.date.getTime(),
published: this.published,
@@ -334,6 +336,44 @@ Playlist.prototype = {
})
});
return doc;
+ },
+ /**
+ * Coarse comparison of data with another playlist
+ * Returns an object containing differing fields
+ **/
+ diff: function (playlist) {
+ // Get the data
+ var thisDoc = this.get_doc();
+ var playlistDoc = playlist.get_doc();
+ // Store anything that differs in an object
+ var diff = {};
+ var field, i, arrayLen;
+ for (field in thisDoc) {
+ // Only care about single level arrays, if anything differs add the whole array
+ if ($.isArray(thisDoc[field])) {
+ arrayLen = thisDoc[field].length;
+ if (arrayLen !== playlistDoc[field].length) {
+ // Lengths differ
+ diff[field] = playlistDoc[field];
+ } else {
+ // Check if any of the elements differ
+ for (i = 0; i < arrayLen; i++) {
+ if (JSON.stringify(thisDoc[field][i]) !== JSON.stringify(playlistDoc[field][i])) {
+ diff[field] = playlistDoc[field];
+ break;
+ }
+ }
+ }
+ } else if (JSON.stringify(thisDoc[field]) !== JSON.stringify(playlistDoc[field])) {
+ diff[field] = playlistDoc[field];
+ }
+ }
+ // Certain keys will always differ
+ delete diff._id;
+ delete diff._rev;
+ delete diff.date;
+
+ return diff;
}
};
/**

0 comments on commit 9e75a2d

Please sign in to comment.