Search code examples
jquery-templatesknockout.js

afterAdd binding is not working


I tried to use the afterAdd binding to add some trivial animation to the elements being added to my observableArray but it does not trigger anything.

I tought I had a problem with my animation code so I coded a small alert on the function but still does not work.

Here's some sample code for the div being templated:

<div id="resultList" 
     data-bind='template: { name: "searchResultTemplate", 
                            afterAdd: function(elem){alert(elem)} }' 
     runat="server">
</div>

This is the template:

<script type="text/html" id="searchResultTemplate">{{each(i, searchresult) resultCollection()}}
<div class="searchresultwrapper ui-corner-all ui-state-default">
    <div class="searchresult">
        <img src='${ ImageUrl }' alt='${ Title }' title='${ Title }' class="searchresultpicture" />
        <div class="searchresultinformationcontainer">
            <span class="searchresulttitle" data-bind="text: Title"></span>
            <br />
            <div class="searchresultdescription" data-bind="text: Description">                   
            </div>
            <span class="searchresultAuthor" data-bind="text: AuthorName"></span> at <span class="searchresultmodule" data-bind="text: ModuleName"></span> on <span class="searchresultdate" data-bind="text: PublicationDate"></span>
            <br />
            <a href='${ Url }' class="searchresultlink">Take me there</a>
        </div>
    </div>
</div>
<br />{{/each}}
</script>

Any ideas?


Solution

  • You need to qualify the template attributes with foreach like so,

    <div id="resultList" data-bind='template: { 
                               name: "searchResultTemplate", 
                               foreach: searchresult,
                               beforeRemove: function(elem) { $(elem).slideUp() },
                               afterAdd: function(elem) { $(elem).hide().slideDown() } 
                               }'  runat="server">
            </div>
    

    and then, not use {{each in the template, just template it for each item stand alone.

    Here, foreach attribute helps keep track of changes to the object array