Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KnockoutJS calling afterAdd function on whitespace elements

Tags:

knockout.js

In general, I'm a big fan of the afterAdd property of the template databinding in KnockoutJS. However, I find that my afterAdd callbacks are always hit 3 times, and I'm not sure why. Am I doing something incorrectly?

Callbacks work like this:

  • Call 1: textnode
  • Call 2: Actual element I care about
  • Call 3: textnode

To cope, all of my handlers end up having a check for isElementContentWhitespace as in the following:

HTML

<ul class="t" data-bind="template: {name: 'itemTmplt', foreach: items, afterAdd: function(elem, idx, val) {my.ko.itemAdd(elem, idx, val);} }">
</ul>
<script id="itemTmplt" type="text/html">
    <li class="tbl" data-bind="attr: {id: name}">
        <h3 data-bind="text: name"></h3>
    </li>
</script>

JS

my.ns("mme.ko");
my.ko = (function () {
    "use strict";

    return {
        itemAdd: function (elem, idx, val) {
            if (elem.isElementContentWhitespace) { return; }

            /*** do stuff here ***/
        }
    };
} ());
like image 833
fordareh Avatar asked Nov 25 '11 00:11

fordareh


1 Answers

afterAdd currently is called foreach node that Knockout finds in your template.

If you do not want to check for the nodeType, then you can strip the whitespace in your template like:

<script id="itemTmplt" type="text/html"><li class="tbl" data-bind="attr: {id: name}"><h3 data-bind="text: name"></h3></li></script>

With this template, you will only see afterAdd called on the li element.

like image 105
RP Niemeyer Avatar answered Oct 23 '22 16:10

RP Niemeyer