0

Data binding is good, very good. But for once it is getting in my way.

I have a default array of users 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?

jdepypere
  • 3,453
  • 6
  • 54
  • 84
  • When you are using an Array/Object and have initialized two-way data-binding, all elements will have the *same reference*. If you change the data, there is no way to stop the others from getting the change, if you want two-way data-binding on *that object*. – Fuzzical Logic Jan 27 '15 at 11:14
  • @FuzzicalLogic: so how can I prevent it then? I just need the array of `item`'s as data bound-objects, not also the users in the it'ms. (an item object has the structure `[{"id" : int, "text": string, "users": [{"id": int, "checked": bool}]}]`) – jdepypere Jan 27 '15 at 11:18

1 Answers1

1

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()};
Ross Allen
  • 43,772
  • 14
  • 97
  • 95
  • 1
    The `slice()` still didn't fix the problem, but the deep copy provided by the link of [this answer](http://stackoverflow.com/a/5344074/1319187) has a few methods that do seem to work. Thanks! – jdepypere Jan 27 '15 at 23:25