简体   繁体   中英

Backbone.js: set a model property within the model?

Working in Backbone.js, I'd like to set a model property from within a method on the model. This seems like it should be simple, but I can't get it to work.

Currently what I have is this. I'm trying to set the 'results' property during a call to 'performSearch':

var SearchModel = Backbone.Model.extend({
    performSearch: function(str) {
      $.get('/' + str, function(results) {
        console.log(data);
        this.set("results", data);
      });
    },
});

This gives me the following error:

Uncaught TypeError: Object #<Object> has no method 'set' 

What am I doing wrong?

The problem is that this is not bound to the model object in the ajax callback.

You can fix it by doing:

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

another way to do this is to explicitly bind callback function to 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
    },
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM