1
我在找出如何在render.onload
函數中訪問this
時遇到問題。我知道答案可能涉及關閉,但我還不能完全圍繞它。Backbone中的文件讀取器範圍問題
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;
}
}
});
您有機會獲得'但this'它不再對同一個對象的引用。在內部函數中,'this'是'reader'。嘗試在外部範圍內分配例如'var model = this.model',然後在內部範圍內分配'model.dataURL = ...'。因此,你利用已經形成的閉合。不需要再組成一個。 –
這很有道理。謝謝! –