2

我正在尝试覆盖 Backbonesync函数以监听progress事件。但是,xhr.upload未定义,因此下面的代码不起作用。有任何想法吗?

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);
  },

  ...

});
4

1 回答 1

3

这是最终对我们有用的方法:

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);
}
于 2013-07-09T17:41:54.773 回答