Reputation: 109
Here is the link to my relevant fiddle: http://jsfiddle.net/mwassmer/Kwmn5/
I'm trying to enable users to move one or more rows from the first table (available database fields) to the second table (fields to be saved to the user's custom "dataset") and vice versa.
I get a "Cannot read property 'isChecked' of undefined" error when the "addSelected" event handler runs unless the last row and only the last row is checked. I'm still trying to wrap my brain around the proper use of "this" in the context of Knockout, so I assume the problem has something to do with my misuse of "this." Any help would be appreciated.
The relevant code excerpt follows:
self.addSelected = function() {
ko.utils.arrayForEach(self.dbRows(), function(row)
{
if (row.isChecked) {
row.isChecked = false;
self.dsRows.push(row);
self.dbRows.remove(row);
}
});
};
Upvotes: 2
Views: 6274
Reputation: 2491
The problem is that you are removing an element of the array you are iterating over.
The source of ko.utils.arrayForEach
is:
var arrayForEach = function (array, action) {
for (var i = 0, j = array.length; i < j; i++)
action(array[i]);
}
One way to solve that is to create a copy of the array before you remove elements. You can do that with:
array.slice(0)
In your code:
self.addSelected = function() {
ko.utils.arrayForEach(self.dbRows().slice(0), function(row)
{
if (row.isChecked) {
row.isChecked = false;
self.dsRows.push(row);
self.dbRows.remove(row);
}
});
};
The updated fiddle is here.
Upvotes: 6