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:
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 ***/
}
};
} ());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With