2

在 Backbone.js 中工作,我想从模型的方法中设置模型属性。这似乎应该很简单,但我无法让它工作。

目前我所拥有的是这个。我试图在调用“performSearch”期间设置“结果”属性:

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' 

我究竟做错了什么?

4

1 回答 1

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

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

   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
    },
});
于 2013-01-08T19:51:07.737 回答