Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout data-bind attribute added dynamically does not trigger the click event handler

Tags:

knockout.js

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 ?

like image 524
user2585299 Avatar asked Mar 04 '14 22:03

user2585299


1 Answers

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);
like image 113
RP Niemeyer Avatar answered Oct 12 '22 12:10

RP Niemeyer