Backbone.js:在模型中设置模型属性?

时间:2013-01-08 19:48:15

标签: javascript backbone.js backbone-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' 

我做错了什么?

1 个答案:

答案 0 :(得分:5)

问题是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);
        });
    },
});

另一种方法是将回调函数显式绑定到model:

   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
    },
});