I have a KnockoutJS view model that creates a list of folders from an observable array. Each of the items in the array have two properties. The folder names need to be oservable because they can be edited by the user.
self.folders = ko.observableArray([{ name: ko.observable('Inbox'), editing: ko.observable(false) }, { name: ko.observable('Vacations'), editing: ko.observable(false) }]); Then, I have a list of objects that go "inside" those folders with several properties, but one of them being the name of the folder. The name of the folder is set to the observable so that if the name changes, the objects stay with the correct folder:
self.emails = ko.observableArray([{ from: 'Sport Clips', subject: '$4 Off', date: '9/6/2015', flagged: ko.observable(false), read: ko.observable(false), selected: ko.observable(false), folder: self.folders()[0].name, attachment:false, }...]); Finally, I have an update function that updates the value of the emails folder parameter based on a user's selection. The problem is that when the user updates the folder location, the actual folder is getting updated with that new name as well (as you'd expect since it is an observable).
self.moveEmails = function() { for(var i = 0; i < self.emails().length; i++) { if (self.emails()[i].selected() == true) { self.emails()[i].folder(this.name()); <-- this is where the name is updated self.emails()[i].selected(false); } } <-- this is just a loop that looks for checked items, it works fine } For example, if I have an object currently in the "Inbox" folder, and a user moves it to the "Business" folder, it updates the email object to have the business folder parameter, but that then causes the Inbox folder to be renamed to Business as well.
Is there any way to prevent this, or is there a better way to write this to avoid this problem?