0

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?

0

1 Answer 1

1

Your email's folder property should be assigned the folder, not its name.

folder: self.folders()[0].name, 

And when you update it, you should assign it a new folder. If this is a folder in your moveEmails function,

self.moveEmails = function() { for(var i = 0; i < self.emails().length; i++) { if (self.emails()[i].selected() == true) { self.emails()[i].folder = this; <-- change folders self.emails()[i].selected(false); } } <-- this is just a loop that looks for checked items, it works fine } 

otherwise you will need to find the appropriate folder based on this.

Sign up to request clarification or add additional context in comments.

2 Comments

Its not an issue of finding the appropriate values. The way the moveEmails function is right now gets the appropriate value.
Although the code didn't help, your comment about assigning it to the folder, not the name solved my problem with a bit of a workaround, thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.