I'm using KnockoutJS and I noticed a problem with bindings that I can explain using this example:
<label><input type="checkbox" data-bind="checked: displayMessage" /> Display message</label>
<div data-bind="if: displayMessage">Here is a message.<span id="super">SUPER</span> Astonishing.</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"></script>
$(function(){
ko.applyBindings({
displayMessage: ko.observable(true)
});
$('#super').on("click", function(){
alert('SUUUUUPER');
});
});
When you first click the "SUPER" span
element the alert shows up. However, if you remove the block by setting the property displayMessage
of the model to false
and putting it back to true
to display it again the binding to the click event is no longer working.
From the source code of if
, ifnot
, and with
bindingHandlers I know that knockout removes the DOM clone and saves it the first time and re appends it using a virtual element API.
So my question is: knowing that the jQuery on()
utility attaches an event handler to the selected element even if they don't exist yet. Is the use of virtual element who's causing the click binding to be lost. If not: explain to me what happens.