fadeIn() inside Knockout's afterAdd callback

47 Views Asked by At

I am trying to learn the foreach binding and I can't understand why the $(element).fadeIn(500) line in the code below isn't working:

ko.applyBindings({
        myItems: ko.observableArray([ 'A', 'B', 'C' ]),
        FadeIn: function(element, index, item) {
          if(element.nodeType == 1){
            $(element).fadeIn(500);
          }
        },
        addItem: function() { this.myItems.push('New item'); }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<ul data-bind="foreach: { data: myItems, afterAdd: FadeIn }">
    <li data-bind="text: $data"></li>
</ul>
 
<button data-bind="click: addItem">Add</button>

The problem is that when I add a new item, it appears in the page without the fadeIn effect.

Codepen -> https://codepen.io/anon/pen/ejxeBr

1

There are 1 best solutions below

1
On BEST ANSWER

It's because your element isn't hidden. Change it to

$(element).hide().fadeIn(500);
// --------^^^^^^^

...or set style="display: none" on it in the markup, but that could be a pain because of the pre-existing elements (which won't get afterAdd calls).

Example:

var count = 0;
ko.applyBindings({
  myItems: ko.observableArray(['A', 'B', 'C']),
  FadeIn: function(element, index, item) {
    if (element.nodeType == 1) {
      $(element).hide().fadeIn(500);
    }
  },
  addItem: function() {
    this.myItems.push('New item');
  }
});
<ul data-bind="foreach: { data: myItems, afterAdd: FadeIn }">
  <li data-bind="text: $data"></li>
</ul>

<button data-bind="click: addItem">Add</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>