0

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?

1
  • Do you push the elements one by one at load time? Commented Jun 6, 2014 at 13:31

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I tried that, but it doesn't seem to make any difference, although I think it does help with performance, so I will look into that later. Here's a fiddle to better illustrate the problem I'm having: jsfiddle.net/norbiu/LqGXL - try clicking on the "Load All at Once" button at the top multiple times. That's what happens when I'm switching between user pages. I clear out the old data to bring in a new userArr.
@Norbert it's always easier with an example. Updated answer. This should work, not very beautiful though :( Another option was to add the animation on the click event of the buttons instead of the foreach binding. Works great for the remove. But it's another story when it comes to adding

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.