Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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**
    });
  }
});
like image 838
Nilesh Kale Avatar asked Nov 30 '22 21:11

Nilesh Kale


2 Answers

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();
like image 188
ismnoiet Avatar answered Dec 18 '22 21:12

ismnoiet


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}); 
    });
  }
});
like image 42
Scott Puleo Avatar answered Dec 18 '22 21:12

Scott Puleo