user1400915 user1400915 - 10 months ago 46
Javascript Question

Dynamic binding of li items click event

I have durandal and knockout web application.
I have a html as follows:

<ul id="header">


In .js function I am adding li dynamically as:

$("#header).append('<li id="btn"><a href="javascript://" data-bind="click:function(data,event) { $root.testmethod(data,event); return true;}"> <span class="name">Test</span></a></li>')


I am aware of the fact that I am binding the li after applyBindings has been called. To add it dynamically I am using
ko.applyBindingsToNode(ul); , but still no luck.

Can anyone please tell me whats the syntax/alternative solution for this?


I would like to answer my own question.

The solution is very simple .

In the .js file define an observable array

self.arraysample = ko.observableArray([]);

In a method populate the array with data


In the html page , we can do this:

<ul id="head" data-bind:"foeach:arraysample">

      <a id="btn">
         <span data-bind="text:$data.arrayelement"></span>

Thats it whenevr the data in the "self.arraysample" changes, automatic updating will take place because of knockout js properties.

I hope it helps someone because ,I have seen so many examples in the web advising to use ko.applyBindings() once again which doesnt work at all.