Question

I have one backbone model containing 10 attributes, Now I want 5 attributes ( out of this 10 attributes ), to be copy/clone in my another newly created model. I can do this thing with getting/setting individually, but I want to know, is there any better/simple way to do this?

example : modelfirst {fld1:value1, fld2: value2 ....}

new modelsecond().set({fld1: modelfirst.attributes.fld1 .... })

I want to do like this:

new modelsecond().set( modelfirst.get('fld1','fld2') });

do some one have any idea?

Was it helpful?

Solution

Use Underscore's methods (since it's required by Backbone, you have access to it):

new modelsecond(_.pick(_.clone(modelfirst.attributes), 'fld1', 'fld2', ...))

To select all the lower case attributes, you should be able to do

new modelsecond(_.pick(
  _.clone(modelfirst.attributes),
  _.select(_.keys(modelfirst.attributes), 
           function(attr){ return /^[a-z]+$/.test(attr) }))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top