Data binding is good, very good. But for once it is getting in my way.
I have a default array of user
s that I insert in each item
on my page. The idea is that each item
has a checkbox for each user
.
Currently I create my emptyUsers
-item like so:
for(var i = 0; i < this.users.length; i++){
this.emptyUsers.push({"id": this.users[i].id, "set": false});
}
note: this.users
is from the db
Then I push this array to every item on my page
item = {"id": data[i].itemId, "text": data[i].text, "users": this.emptyUsers};
note: data
is from the db
The issue now is that when I change the set
-attribute of one of the users in an item, the set
-attribute gets changed for all items for that user. I presume this is due to data binding coming in to play somewhere since I use push()
to insert the users in the item. Is this indeed the case, and how can I prevent this behaviour?
This is happening because you are giving each object a reference to the one emptyUsers
array. If each object should have its own array from the start, you can create a copy when you first bind the data by calling slice()
on emptyUsers
. This will create only a shallow copy; if you need each object to also have their own copies of the elements in the array you should search for "js array deep copy":
item = {"id": data[i].itemId, "text": data[i].text, "users": this.emptyUsers.slice()};