4
votes

I've a model listen on the vent for a event update:TotalCost, which is triggered from (unrelated) Collection C when any model M belonging to collection C changes.

This event is coded in the initialize method as below. On receiving the event I get the following error:

TypeError: this.set is not a function
this.set({ "totalsale": value});

CostModel = Backbone.Model.extend({     
  defaults: {
    totalSale: 0,
    totalTax: 0
  },

  initialize: function(attrs, options) {
    if(options) {
      if(options.vent) {
        this.vent = options.vent;
      }
    }
            
    this.vent.on("update:TotalCost", function(value) {
      this.set({ "totalSale": value}); **//ERROR HERE**
    });
  }
});
7

7 Answers

3
votes

Have you tried using a closure?

CostModel = Backbone.Model.extend({     
  defaults: {
    totalSale: 0,
    totalTax: 0
  },
  initialize: function(attrs, options) {
    var self = this;

    if(options) {
      if(options.vent) {
        this.vent = options.vent;
      }
    }

    this.vent.on("update:TotalCost", function(value) {
      self.set({ "totalSale": value}); 
    });
  }
});
12
votes

It is highly possible you've forgot to add the new keyword before your model for example you have:

var user = UserModel();

// instead of 

var user = new UserModel();
3
votes

Perhaps you want this to refer to current CostModel instance, to do so you need to pass this to this.vent.on call so event callback will be executed in context of model:

this.vent.on("update:TotalCost", function(value) {
    this.set({ "totalSale": value});
}, this);
1
votes

it may be due to 'set' works on model not on object. so you can, first convert your object in to model then try..

in example:

new Backbone.Model(your_object).set('val', var);
0
votes

Another cause of this error can be if you try to create a new model without using the "new" keyword

0
votes

I was getting this mysterious error when using it with Parse. I had:

Parse.User().current().escape("facebookID")

... when I should have had:

Parse.User.current().escape("facebookID")

Removed the extra () and it works fine now.

0
votes

Another cause:

// render() method in view object
setInterval(this.model.showName, 3000);

// showName() method in model object
showName: function(){
    console.log(this.get('name')); // this.get is not a function
}