Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

nested attributes don't get cloned correctly with Model.toJSON #2373

Closed
markbrown4 opened this Issue · 6 comments

4 participants

Mark Jeremy Ashkenas Ryan Leckey mansiemans
Mark

json = model.toJSON()
console.log json.observation.read_at
"2013-03-13T23:30:00Z"

/* setting this persists it on the model itself and not the cloned object. */
json.observation.read_at = 'FOOBAR!!'
json = model.toJSON()
console.log json.observation.read_at
"FOOBAR!!"

Mark

http://underscorejs.org/#clone

Looks like we need a deep clone happening here instead.

Jeremy Ashkenas
Owner

Yep. toJSON and _.clone are shallow. That's how it's supposed to work.

Jeremy Ashkenas jashkenas closed this
Mark

I can see the discussion here:
jashkenas/underscore#162

So, when you use Backbone you should never have objects with nested attributes?

I was able to get around it with this:
json = jQuery.extend true, {}, model.attributes

Still feels nasty.

Ryan Leckey

So, when you use Backbone you should never have objects with nested attributes?

That's fine to have. But currently it is expected behavior for the serialization done by toJSON to not be deep.

I've suggested somewhere in the pile of issues to switch the implementation to something like what we've added in chaplin: https://github.com/chaplinjs/chaplin/blob/master/src/chaplin/models/model.coffee#L72-L77. It's faster for common cases and allows modification of the resultant object safely (without changing the model).

Mark

Interesting. It sounds like the shallow copy has tripped up a few people.

mansiemans

The expected behavior is unexpected.

meta-level unlocked

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.