我无法弄清楚如何在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;
}
}
});
答案 0 :(得分:4)
在该函数范围之外创建对this
的引用,如下所示:
var self = this; // or var that = this;
reader.onload = function() {
// access `this` using `self`
self.model.dataURL = event.target.result;
}