At first, I have a Button addTemplate that will add html to my body via Knockout and jQuery:
<button data-bind="click: addTemplate">Add Template</button>
<script type="text/html" id="MyTemplate">
<div id="container">
<a href="#" data-bind="click: $root.doAlert">Do Alert</a>
</div>
</script>
The added Template has some knockout Bindings, too. They should activate an Alert in my ViewModel:
function MyViewModel()
{
self = this;
self.addTemplate = function () {
$($("#MyTemplate").html()).appendTo("body");
}
self.doAlert = function() {
alert('Hello World');
}
}
ko.applyBindings(new MyViewModel());
When I click on the Link in my added Template, the doAlert function does nothing.
I do not want to use string-chained HTML Templates in my ViewModel.
Here is the Fiddle: http://jsfiddle.net/tgu8C/5/
You should apply binding to newly added element.
var newElement = $($("#MyTemplate").html()).appendTo("body");
ko.applyBindings(self, newElement);
JSFiddle DEMO
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