Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override backbone 'set' method

Tags:

backbone.js

I want to override backbone set method so that whenever I set a value to backbone Model the callbacks registered on that attribute get called without checking for same previous value of that attribute .

var model = Backbone.Model.extend({
     defaults : {
         prop1 : true 
     }
});

var view = Backbone.View.extend({
     initialize : function(){
        this.listenTo(this.model,"change:prop1", this.callback);

     },
     callback : function(){
        // set is called on prop1
     }
});

var m1 = new model();
var v1 = new view({model:m1});
m1.set("prop1",true); // It doesn't trigger callback because I'm setting the same value to prop1
like image 819
radhe001 Avatar asked Jul 29 '13 11:07

radhe001


People also ask

Is backbone a MVC?

Structure of a Backbone.Backbone. js is based on the MVC pattern. Modules that define interfaces or handle data use Backbone. js to define routers, views, and models/collections.

Does backbone need jQuery?

You can use the Backbone. Model without jQuery, but Backbone.


1 Answers

You can write a new method in backbone model set like this :

var model = Backbone.Model.extend({
     defaults: {
         prop1: true;
     },

     // Overriding set
     set: function(attributes, options) {
        // Will be triggered whenever set is called
        if (attributes.hasOwnProperty(prop1)) {
           this.trigger('change:prop1');
        }  

        return Backbone.Model.prototype.set.call(this, attributes, options);
     }
});   
like image 197
Rishabh Singhal Avatar answered Nov 10 '22 13:11

Rishabh Singhal