The Backbone model gives this.set no function in Model.initialize

I have a model that listens for ventilation for the "update: TotalCost" event, which is fired from the (unrelated) collection C when any model M related to collection C changes.

This event is encoded in the initialization method, as shown below. When I receive an event, I get the following error:

TypeError: this.set is not a function of 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** }); } }); 
+4
source share
7 answers

Did you try to use 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}); }); } }); 
+3
source

You may have already forgotten to add new in front of your model, for example:

 var user = UserModel(); // instead of var user = new UserModel(); 
+10
source

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

 this.vent.on("update:TotalCost", function(value) { this.set({ "totalSale": value}); }, this); 
+3
source

this may be due to the 'set' working with the model not on the object . so you can convert your object to a model first and then try.

in the example:

 new Backbone.Model(your_object).set('val', var); 
+1
source

Another reason for this error may be if you try to create a new model without using the β€œnew” keyword.

0
source

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

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

... when I should have:

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

Deleted extra () and now it works fine.

0
source

Another reason:

 // 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 } 
0
source

Source: https://habr.com/ru/post/1478976/


All Articles