Reputation: 25
Can i generate knockoutJS bind dynamically
using for example
$("el").html("<span data-bind=\"value:name\"></span>
Upvotes: 1
Views: 146
Reputation: 453
The template binding might be a better solution here. This allows you to add elements dynamically without the need to call ko.applyBinding()
each time.
<el data-bind="template: { name: 'name-template', foreach: names }"></el>
<script id="name-template" type="text/template">
<span data-bind="value: name"></span>
</script>
Upvotes: 3
Reputation: 11493
You can, but each binding you add will not be effective unless you rebind the model to the DOM using ko.applyBinding(). Only then Knockout will recognize the binding and apply it to the model given.
However, perhaps you're actually looking for a way to add nested content dynamically? That is, KnockoutJs allows you bind arrays also, so that html is added/removed automatically as you manage your array:
<el data-bind="foreach:names">
<span data-bind="value:name"></span>
</el>
Upvotes: 1