backbone.jsunderscore.jsmarionettebackbone-eventsbackbone-model

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

Solution

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