Backbone中的FileReader范围问题

时间:2013-06-22 00:05:06

标签: javascript backbone.js closures

我无法弄清楚如何在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;
    }
  }

});

1 个答案:

答案 0 :(得分:4)

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

var self = this; // or var that = this;
reader.onload = function() {
    // access `this` using `self`
    self.model.dataURL = event.target.result;
}