Explanation on these two images


The code
showUserProfile: (user_data)->
console.log "Routers.AppRouter showUserProfile()", user_data
window.user_profile = user_data
playlists_both_people = user_profile['playlists']
my_profile['playlists'].forEach (pl)-> playlists_both_people.push(pl)
@playlists = new Playlists.Collections.PlaylistsCollection( playlists_both_people )
$("#app").html( new Playlists.Views.User.ShowView(user_data).render().el )
@ok()
Now that everyone has finished beating you up, I’ll be nice and show you what you’re doing wrong.
You have a simple referencing problem. You start out with the
user_dataobject being passed to your function. Then you make another reference to whatuser_datapoints at here:Now your data looks like this:
Then you make another reference to
user_data.playlistshere:And now you have this on your hands:
And then you push a bunch of things onto the
playlists_both_peoplearray and wonder why it changeduser_data.playlistsas well. The diagram tells you why: you never made a copy of anything, you’re just referencing the same piece of data through multiple variables.You’re using Backbone so you have Underscore, perhaps
_.clonecan help you:That will give you a (shallow) copy of
user_profile.playlists(which is the same asuser_data.playlistsat this point) inplaylists_both_peopleand the nextforEachwon’t change anything inuser_data.Note that you still might have a double reference problem with
window.user_profile. You can’t use just one_.cloneto fix this possible problem though, you’d have to clone each member separately since_.cloneonly does shallow copies. However, you probably have jQuery around and$.extendsupports deep copying so that might be an option.I’d also recommend against putting things directly in
window. You’d be better off setting up a namespace for your application, saywindow.app, and then use that namespace: