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

Ric*_*ard 2 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);
      });
    },
});
Run Code Online (Sandbox Code Playgroud)

这给了我以下错误:

Uncaught TypeError: Object #<Object> has no method 'set' 
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

sou*_*eck 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);
        });
    },
});
Run Code Online (Sandbox Code Playgroud)

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

   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
    },
});
Run Code Online (Sandbox Code Playgroud)