使用progress事件侦听器覆盖Backbone同步

时间:2013-07-09 14:44:05

标签: javascript jquery events backbone.js

我正在尝试覆盖Backbone sync函数以便侦听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);
  },

  ...

});

1 个答案:

答案 0 :(得分: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);
}