In the viewAttached event of my viewmodel, I am creating a dynamic anchor element as follows:
qaItemLink = document.createElement("a");
$(qaItemLink).attr({ 'class': 'qaTreeItem', 'href': '#', 'data-bind': 'click:$root.showQaItemDetails' });
which when checked in UI is rendered as below:
<a class="qaTreeItem" href="#" data-bind="click:$root.showQaItemDetails">Item 1</a>
I don't see any problem in the anchor tag being rendered. What could be the reason that the function showQaItemDetails is not getting called ?
If the element was added after ko.applyBindings
was called, then Knockout would not have had a chance to bind it. If you are using the template
binding (or with
, foreach
, etc.) to add dynamic content, then Knockout takes care of this for you. This is generally the best approach.
In your case, if possible, you could wait to call ko.applyBindings
until the content has been added.
You can also directly bind an element by calling ko.applyBindings(viewModel, element)
. This will bind the element and its children. However, I don't know in your case what context your anchor needs to be bound against (root vs. some nested item).
It is also possible to use ko.applyBindingsToNode
(or in 3.0 ko.applyBindingAccessorsToNode
passing a function that returns the binding) to directly apply a binding like:
ko.applyBindingsToNode(qaItemLink, { click: viewModel.showQaItemDetails }, optionalContext);
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