It seems Knockout’s convenient “afterRender” method on foreach bindings only fires when data is added, and not removed.
You can test that here – http://jsfiddle.net/farina/4BaXs/1/ by clicking load initial, seeing the four alerts, then clicking load delete and notice nothing happens.
So, to solve this problem I decided to attempt to create a manual subscription to my ko.mapping.fromJS array, but that just results in a call every time I update the data from AJAX, even if the data hasn’t changed.
I feel like the mapping plugin is somehow failing, and thinking that the data is always new, even when it is not.
Is there some sort of event which only occurs when the array has changed? My subscriptions on individual items work as expected, but obviously you can’t subscribe to an entire list of items?
I wrote up a function that uses
ko.utils.compareArraysto figure out what has changed.compareArraysis also used by theforeachbinding. I also took your example and updated it to use this function. Here it is: