I am having some problems getting KnockoutJs beforeRemove and afterAdd handlers to fire.
This is the relevant code fragment
function viewModel(list) {
var self = this;
this.items = ko.observableArray(list);
this.removeItem = function(item) {
self.items.remove(item);
}
this.removeFirst = function() {
self.removeItem(self.items()[0]);
};
this.onRemove = function(elements) {
console.log("Updating");
$(elements).addClass('transition-out');
};
}
ko.applyBindings(new viewModel(items));
And this markup
<button data-bind="click: removeFirst">Remove first</button>
<ul data-bind='foreach: items, beforeRemove: onRemove'>
<li data-bind="text: name, click: $parent.removeItem"></li>
</ul>
I am seeing list updates but the onRemove handler is never fired.
I’ve created a JSFiddle to illustrate the problem.
Thanks,
Gene
The syntax that you want to use looks like:
beforeRemoveis an option that is accepted by theforeach(and ultimately thetemplate) binding. It was being treated as a separate binding in the way that you were specifying it. If a binding does not exist, then it is ignored (some binding are accessed via allBindingsAccessor, so KO wouldn’t know that and doesn’t throw an error).Also, the function will get called once for each node in your “template”. In your case it will be a text node, the
li, and another text node. If you want to ignore the text nodes, then check that the element’s (first argument) nodeType is 1.