javascript - How to clone models from Backbone collection to another -
i need clone models in 1 backbone collection , add add them another. (iow of models in new collection need unique, , have no connection models in original collection.)
here code:
collection1.each(function( model ) { var clone = new backbone.model( model.tojson() ); clone.set( this.idattribute, null, { silent: true }); collection2.add( clone ); }); this doesn't quite work. can add model collection1 collection2 once. if try second time, fails. somehow backbone detecting dup.
any suggestions on doing wrong?
thanks (in advance) help
in code provided, this.idattribute not think , won't create models without ids, leading collisions when copy models second time.
underscore hard dependency of backbone, can use _.omit on json representation of collection filter out ids. example,
function copycollection(collection1, collection2){ var idattribute = collection1.model.prototype.idattribute; var data = _.map( collection1.tojson(), function(obj){ return _.omit(obj, idattribute); } ); collection2.add(data); } var c1 = new backbone.collection([ {id: 1, name: "n1"}, {id: 2, name: "n2"} ]); var c2 = new backbone.collection(); copycollection(c1, c2); copycollection(c1, c2); console.log(c2.tojson()); and fiddle http://jsfiddle.net/jt59v/
Comments
Post a Comment