Backbone Model gives this.set not a function in Model.initialize

Nilesh Kale picture Nilesh Kale · May 3, 2013 · Viewed 8.8k times · Source

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

Answer

ismnoiet picture ismnoiet · Mar 31, 2016

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();