Override backbone 'set' method

匿名 (未验证) 提交于 2019-12-03 03:00:02

问题:

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 

回答1:

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


回答2:

Actually, the signature of function set differs from the one depicted in the accepted answer.

export var MyModel = Backbone.Model.extend({     set: function (key, val, options) {         // custom code         var result = Backbone.Model.prototype.set.call(this, key, val, options);         // custom code         return result;     } }); 

See:



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!