2

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?

Richard
  • 62,943
  • 126
  • 334
  • 542

1 Answers1

5

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
    },
});
soulcheck
  • 36,297
  • 6
  • 91
  • 90