nilbus/Backbone.dualStorage

Fire event when syncDirtyAndDestroyed is finished

da1nerd opened this issue · 1 comments

This is a great extension, however there are times when it would be super convenient to know when syncDirtyAndDestroyed was done.
In particular I need to load the models from localstorage, then push the pending changes to the server, then download updates from the server.

I've created a little patch that does that. This is kinda hacky and doesn't completely cover all the corner cases, but it's at least a starting point.

I've added the following to the top of the syncDirtyAndDestroy method:

   var that = this;
    options = options || {};
    var numChanges = 0;
    var numCalls = 0; // we are expecting two
    options.success = options.error = function() {
      numChanges --;
      if(numChanges === 0) {
        that.trigger('sync:localstorage');
      }
    };
    this.on('localstorage:numchanges', function(count) {
      numCalls ++;
      numChanges += count;
      if(numChanges === 0 && numCalls == 2) {
        that.trigger('sync:localstorage');
      }
    });

I've inserted this in both the syncDestroyed and syncDirty methods just before the for loop:

this.trigger('localstorage:numchanges', ids.length);

Now I can bind to sync:localstorage to be notified when everything is finished.

I agree with you that this would be a very useful feature. The good news is that this will be built into the future version 2.0 (and currently the not-yet-production-ready async branch). The bad news is that no one is actively working on that feature at the moment.

In the async branch and later in 2.0, syncDirtyAndDestroyed will return a jQuery promise, so you will be able to do this:

myCollection.syncDirtyAndDestroyed().then(function() {
  // do something when it's done
});