knockout.js - KO Template with Foreach If condition causing afterAdd not to fire -
in example below you'll see dosomething never fires. if remove if: comments
templating binding dosomething fire expected. know happening cause this? occurs while using data
attribute on template binding handler.
i using knockout 2.2.1. jsfiddle http://jsfiddle.net/yadzx/2/
<div data-bind="template: { if: comments, name: 'comments' }"></div> <script type="tmpl" id="comments"> <div data-bind="foreach: { data: comments, afteradd: $root.dosomething }"> <div data-bind="text: name"></div> </div> </script> <script> var vm = { comments: ko.observablearray([{name:'hey'}]), dosomething: function (element, index, data) { $(element).addclass('wow'); } }; ko.applybindings(vm); vm.comments.push({name:'foo'}); vm.comments.push({name:'bar'}); </script>
the if
condition on template
binding causes update whenever comments
changes. knockout re-render entire template , previous state of foreach
binding lost.
there few ways work around depending on side-effects want or don't want.
remove
if
option. code still work, you'll have<div>
foreach
binding in html. isn't option if messes layout.split
if
template
, use element (or comment-syntax)if
binding. work long you're using version 2.2.0 or higher of knockout.<script type="tmpl" id="comments"> <!--ko if: comments--> <div data-bind="foreach: { data: comments, afteradd: $root.dosomething }"> <div data-bind="text: name"></div> </div> <!--/ko--> </script>
instead of using
if
binding, usevisible
binding, hides current element , not re-render.<script type="tmpl" id="comments"> <div data-bind="visible: comments, foreach: { data: comments, afteradd: $root.dosomething }"> <div data-bind="text: name"></div> </div> </script>
one thing consider, though, observablearray
won't contain falsy value. that's because in javascript, empty array still truthy. if want test empty array, you'll need change if: comments
if: comments().length
.
Comments
Post a Comment