I am having an issue with the knockoutjs if binding. I use the binding quite liberally because it allows me to reference sub properties in my bindings without errors.
The one cause for concern is registering event handlers and so forth on DOM elements which are added by the if binding. Basically I need to get a callback when the elements added by the if binding are added to the DOM. I have tried using the livequery jquery plugin but it seems like the elements are being added twice. I came up with some example code to show this.
The knockout docs clearly state:
“The if binding, however, physically adds or removes the contained markup in your DOM, and only applies bindings to descendants if the expression is true.”
http://knockoutjs.com/documentation/if-binding.html
However in the following code, the alert in the inline script IS executed:
JS:
var vm = {
val: ko.observable(false),
someText: ko.observable("some text"),
};
ko.applyBindings(vm, document.getElementById("d1")
HTML:
<div id="d1" data-bind="if: val">
<span data-bind="text: someText"></span>
<script>alert("here")</script>
</div>
You have essentially answered your own question with this quote:
While this quote clearly indicates the behavior of bindings, it does not state anything about other JavaScript or browser functionality. This makes perfect sense since Knockout’s domain are its bindings and nothing else. By the time Knockout has been loaded, your browser will have already executed that alert-statement. And it will execute that alert-statement every time Knockout adds it back to the DOM-tree.
Using
<script>elements like this in combination with Knockout is bad practice and can lead to unpredictable behavior. What you want to do is express the intended behavior in the domain of Knockout, which are its bindings. In your case, this would fit theafterRenderbinding:If
valistruethen the inner<span>is rendered and theafterRenderevent will fire.If
valisfalsethen the inner<span>will be not be rendered and theafterRenderevent will not fire.