Knockoutjs data file creates multiple items

I'm trying to find out knockouts. So I was reading an entry from this URL http://knockoutjs.com/documentation/foreach-binding.html

I am just trying to run the code from the above url, but when I click the button more than one item is created Li

, it should only create one.

here is the html code

<ul data-bind="foreach: { data: myItems, afterAdd: yellowFadeIn }">
    <li data-bind="text: $data"></li>
</ul>

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

      

JS code

ko.applyBindings({
        myItems: ko.observableArray([ 'A', 'B', 'C' ]),
        yellowFadeIn: function(element, index, data) {

            $(element).filter("li")
                      .animate({ backgroundColor: 'yellow' }, 200)
                      .animate({ backgroundColor: 'white' }, 800);
        },
        addItem: function() {this.myItems.push('New item'); }
    });

      

the above code was posted to the js knockout tutorial page but it doesn't work as expected. I also verified that the jquery animation function is called but does not change the bg color. What's wrong with the code?

+3


source to share


1 answer


You need jQuery to run this part:

$(element).filter("li").animate({ backgroundColor: 'yellow' }, 200).animate({ backgroundColor: 'white' }, 800);

      

If you don't have jquery, the yellowFadeIn function will fail and apparently the knockout will try to reapply previous attempts on every click.

see how you edited the script: http://jsfiddle.net/jkrxv8e8/2/



Note that the jQuery documentation for it animate

states that the property background-color

cannot be animated unless jquery.color is used .

There is a script here with the corresponding plugin added

http://jsfiddle.net/jkrxv8e8/3/

+4


source







All Articles