I’ve got a table updated with each entry in my model and two events fired on removal and addition to the array. hideElement calls the jquery “fadeOut” and showElement calls the jquery “fadeIn” functions to create a nifty fade-out/fade-in effect.
<tbody data-bind='template: { foreach: entries,
beforeRemove: hideElement,
afterAdd: showElement }'>
My model is like this:
var Model = function() {
self.entries = ko.mapping.fromJS([]);
this.getData = function() {
$.ajax({
url: "/test",
type: "GET",
success: function(response) {
ko.mapping.fromJS(response, self.entries);
...
this.showElement = function(elem) {
if(elem.nodeName == "TR") {
$(elem).fadeIn(500);
}
};
this.hideElement = function(elem) {
if(elem.nodeName == "TR") {
$(elem).fadeOut(500);
};
};
...
The problem is that each time the ko.mapping.fromJS(response, self.entries) is called in the ajax response it seems like knockout are removing/adding the entries even if they are exactly the same. Because of that the showElement/hideElement is called and elements in my table are “flashing” since they are removed/added each ajax call.
Is it suppose to be like this or am I using it wrong?
You need to use the key option in the mapping plugin so that the plugin knows which items are the same
http://jsfiddle.net/yWwfz/