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
It's because your element isn't hidden. Change it to
...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 getafterAdd
calls).Example: