I have an array of users that I get via Ajax when the page loads and I list them using the foreach
binding, like this:
<div data-bind="foreach: { data: usersArr,
afterAdd: showElement,
beforeRemove: fadeRemove }">
I want the list to show up on page load without the fadeIn()
effect I apply to it using afterAdd
and to disappear when I empty the usersArr
array, without beforeRemove
firing.
I only want the effects to fire when adding a new user or deleting an existing one.
Is there a way to achieve this?
Load all your data at once in your userArr
instead of pushing them one by one:
viewmodel.userArr(receivedArray); //instead of viewmodel.userArr.push(newElement)
EDIT
The above does not work. The afterAdd
and beforeRemove
bindings do not care how the elements are added/removed, they will be called in any case.
Here is an ugly trick: add a allowAnimation
variable to your viewmodel and run the code only when it is set (told you it's ugly):
ViewModel.prototype.showElement = function(elem, index, user) {
if (user.allowAnimation) {
if (elem.nodeType === 1) {
$(elem).hide().fadeIn();
user.allowAnimation = false;
}
}
};
ViewModel.prototype.fadeRemove = function(elem, index, user) {
if (user.allowAnimation) {
if (elem.nodeType === 1) $(elem).fadeOut(500, function() {
$(elem).remove();
user.allowAnimation = false;
});
} else {
$(elem).remove();
}
};
ViewModel.prototype.addUser = function() {
this.usersArr.push({name: 'bla', allowAnimation: true});
};
ViewModel.prototype.removeUser = function(user) {
user.allowAnimation = true;
this.usersArr.remove(user);
};
Check this fiddle