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

Closed
markbrown4 opened this Issue Mar 14, 2013 · 6 comments

Projects

None yet

4 participants

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!!"

http://underscorejs.org/#clone

Looks like we need a deep clone happening here instead.

Owner

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

@jashkenas jashkenas closed this Mar 14, 2013

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.

mehcode commented Mar 14, 2013

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).

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

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