David Jones
David Jones

Reputation: 10239

Overriding Backbone sync with a progress event listener

I'm attempting to override the Backbone sync function in order to listen to progress events. However, xhr.upload is undefined, so the code below isn't working. Any ideas?

var Model = Backbone.Model.extend({

  ...

  sync: function(method, model, options) {
    options.beforeSend = function(xhr) {
      xhr.upload.addEventListener("progress", function(event) {
        if (event.lengthComputable) {  
          var percentComplete = event.loaded/event.total;
          console.log(percentComplete);
        }
      }, false); 
    }
    return Backbone.sync(method, model, options);
  },

  ...

});

Upvotes: 2

Views: 701

Answers (1)

David Jones
David Jones

Reputation: 10239

Here's what finally worked for us:

sync: function(method, model, options) { 
  options.beforeSend = function(xhr, settings) {
    settings.xhr = function() {          
      var xhr = $.ajaxSettings.xhr();
      xhr.upload.addEventListener("progress", function (event) {
        Math.ceil(event.loaded/event.total*100);
      }, false);
      return xhr;
    }
  }
  return Backbone.sync(method, model, options);
}

Upvotes: 3

Related Questions