[英]Backbone.js: set a model property within the model?
在Backbone.js中工作時,我想從模型的方法內設置模型屬性。 這看起來應該很簡單,但是我無法使其正常工作。
目前我所擁有的是這個。 我試圖在調用“ performSearch”的過程中設置“ results”屬性:
var SearchModel = Backbone.Model.extend({
performSearch: function(str) {
$.get('/' + str, function(results) {
console.log(data);
this.set("results", data);
});
},
});
這給了我以下錯誤:
Uncaught TypeError: Object #<Object> has no method 'set'
我究竟做錯了什么?
問題在於, this
未綁定到ajax回調中的模型對象。
您可以通過執行以下操作來修復它:
var SearchModel = Backbone.Model.extend({
performSearch: function(str) {
//assign to local variable, so that it is accesible in callback's closure
var self = this;
$.get('/' + str, function(results) {
// are you sure it should be data?
console.log(data);
self.set("results", data);
});
},
});
另一種方法是將回調函數顯式綁定到模型:
var SearchModel = Backbone.Model.extend({
performSearch: function(str) {
//assign to local variable, so that it is accesible in callback's closure
$.get('/' + str, (function(results) {
// are you sure it should be data?
console.log(data);
this.set("results", data);
}).bind(this)); //binding here
},
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.