backbone.js - Backbone Model change data in one instance affects another -


i had weird bug when using backbone.model

so have model declaration like:

var mymode = backbone.model.extend({    defaults:{       'somelist': []    },     initialize: function(){       _.bindall(this, 'tostring', 'castfromstring');    },     tostring: function(){       return this.get('hierarchynamelist').join('+');    },     castfromstring: function(str){       var strarray = [], index = 0;       if (str) {          strarray = str.split('+');       }       (index = 0; index < strarray.length; index++){          this.get('hierarchynamelist').push(strarray[index]);       }    } }); 

then tried test it

(function () { 'use strict';  var assert = function(condition, message) {     if (condition !== true) {         throw message || "assertion failed";     } };  var ma = new mymodel({'somelist': ['a','b','c']}); var mb = new mymodel(); mb.castfromstring('a+b+c');  //i have added equals function array prototype , tested assert(ma.get('somelist').equals(mb.get('somelist')));     //true  var mc = new mymodel(ma.tojson());    //behaves expected var md = new mymodel();   //for reason list contains list b md.castfromstring(mb.tostring());    //since castfromstring used push, b , d both has array of length 6  assert(mc.equals(ma));    //success assert(mc.equals(md));    //fail, mc has arraylength 3, md has 6    }).call(this); 

the actual code more complicated this, think doing wrong, suggestion on why happen? in advance!

the problem defaults

defaults:{   'somelist': [] }, 

objects in javascript passed reference not value. means instances, didn't explicitly specified somelist value share array created in defaults definition above. avoid can define defaults function:

defaults: function () {     return { 'somelist': [] }; }, 

this create new array every instance of mymodel, won't share same array.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -