javascript - Backbone Model array property change and change event listener not always firing -
this question has answer here:
i found strange in backbone using change events. it's model wich has array property. , if property push new value inside , set model change event not fired...
here's documented example:
var testmodel = backbone.model.extend({ defaults : { numbers : [] }, initialize : function() { this.on('change:numbers', this.changedevent); }, changedevent : function() { console.log('model has changed'); } }); var otestmodel = new testmodel(); otestmodel.set('numbers', [2, 3, 4]); // change:numbers event fired var anumbers = otestmodel.get('numbers'); anumbers.push(5); otestmodel.set('numbers', anumbers); // change:numbers event not fired why??? // otestmodel.set('numbers', [2, 3, 4]); // if line not commented out change:numbers event fired console.log(otestmodel.tojson()); // dumps out [2,3,4,5] respective [2,3,4] if line above not commented out
thx in advance.
hesson absolutely right about:
arrays in javascript treated pointers, mutating array not change pointer, , no "change" event fired.
however, alternate solution (if using underscore.js) can do:
var anumbers = _.clone(otestmodel.get('numbers')); anumbers.push(5); otestmodel.set('numbers', anumbers); //will trigger changed:numbers event
as seen in answer similar problem: backbone.js : change not firing on model.change()
this duplicate object instead of making reference, nested objects or arrays references.
Comments
Post a Comment