Last active
August 29, 2015 14:05
-
-
Save Rob-ot/8b1b8cb69836ac034375 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## create a RObject wrapped array of user models | |
users = new RObject [ | |
{ id: 'a', name: 'Rob' } | |
{ id: 'b', name: 'Bob' } | |
{ id: 'c', name: 'Jack' } | |
{ id: 'd', name: 'Jill' } | |
] | |
## create a RObject wrapped array of blog models | |
blogs = new RObject [ | |
{ title: 'How to a', creatorId: 'a' } | |
{ title: 'How to c', creatorId: 'c' } | |
{ title: 'How to b', creatorId: 'b' } | |
] | |
## convert list of models into an object keyed by id | |
usersById = users.indexBy('id') | |
## create a new array of blog models that | |
## include a full user model looked up by creatorId | |
richBlogs = blogs.map (blog) -> | |
blog.extend { creator: usersById.prop(blog.prop('creatorId')) } | |
## as expected, the 'How to c' blog has a full user object with username and all | |
richBlogs.at(1).prop('creator').prop('name') # == Jack | |
## change the blog author id of 'How to c' to Jills id | |
blogs.at(1).prop('creatorId').set('d') | |
## when the user id was changed, the full creator was automatically updated to Jills user object | |
richBlogs.at(1).prop('creator').prop('name') # == Jill | |
## change a users name | |
usersById.prop('d').prop('name').set('Leroy') | |
## the full user here is also automatically updated | |
richBlogs.at(1).prop('creator').prop('name') # == Leroy | |
## add a new blog with a creator that doesn't exist | |
blogs.push { title: 'One weird trick', creatorId: 'e' } | |
## accessing that creator gives null right now | |
richBlogs.at(3).prop('creator').prop('name') # == null | |
## create a new user with the same id as the one of the blog we just created | |
usersById.push { id: 'e', name: 'ZZ-top' } | |
## the full user model is automatically added to the blog based on id | |
richBlogs.at(3).prop('creator').prop('name') # == ZZ-top |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment