1

我无法弄清楚如何this在下面的render.onload函数中访问。我知道答案可能涉及闭包,但我还不能完全理解它。

var PhotoModel = Backbone.Model.extend({

  initialize: function() {
    this.uploadPhoto();
  },

  uploadPhoto: function() {
    var file = this.get("file");
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function(event) {
      // I don't have access to "this" here...
      this.dataURL = event.target.result;
    }
  }

});
4

1 回答 1

4

创建this对该函数范围之外的引用,如下所示:

var self = this; // or var that = this;
reader.onload = function() {
    // access `this` using `self`
    self.model.dataURL = event.target.result;
}
于 2013-06-22T00:11:12.193 回答