Leonardo
Leonardo

Reputation: 11391

Do something when a foreach data-binding is completed

In my form a list is "filled" by knockout. Here's the ul code:

<ul class="sortable ui-widget-content" data-bind="foreach: menus">
   <li>
      <a href="#" data-bind="attr: { title: name }, click: $parent.navigate">
         <i data-bind="attr: { class: iconClass }"></i>
             <span data-bind="text: title"></span>
       </a>
   </li>
</ul>

And it works just fine. What I need now is that when the foreach is done, run a piece of code. Any ideas on how to implement that?

Upvotes: 0

Views: 104

Answers (1)

rakhmanoff
rakhmanoff

Reputation: 369

From Knockout Documentation: (look at afterRender, note 7)

If you need to run some further custom logic on the generated DOM elements, you can use any of the afterRender/afterAdd/beforeRemove/beforeMove/afterMove callbacks

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

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

<script type="text/javascript">
    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'); }
    });
</script>

Are you looking something like this?

EDIT: In this case afterRender should be ok

Upvotes: 4

Related Questions