Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I bind new elements using knockout?

How can I bind a new element create after the page has loaded?

I have something like this

system = function()
{

    this.hello = function()
    {
        alert("hello");
    }

    this.makeUI = function(container)
    {
        div = document.createElement("div");
        div.innerHTML = "<button data-bind='click: hello'>Click</button>";
    }
}

ko.applyBindings(new system);

If I try this

this.makeUI = function(container)
{
    div = document.createElement("div");
    div.innerHTML = "<button data-bind='click: hello'>Click</button>";
    ko.applyBindings(new system,div);
}    

but according to these posts it will not work.

like image 441
BlaShadow Avatar asked Apr 07 '12 01:04

BlaShadow


1 Answers

The goal with knockout is to only call knockout once on a set of dom elements. Hence if you call applyBindings repeatedly on the whole document you will have issues with multiple bindings.

There are a few cases where calling applyBindings multiple times is justified and this is in the case of partial views which were not in the dom at the time of the first binding and hence were not bound. You can bind these by selectively scoping the applyBindings to that dom element.

Here's an example of what you were trying to achieve. Your problem was that you weren't inserting the node you created.

http://jsfiddle.net/madcapnmckay/qSqJv/

I would not recommend this approach for this particular example, there is a better way.

If you want to create dom elements dynamically and have them bound by knockout, the most common approach is to use the built in templating functionality which takes care of inserting the elements and binding any data-bind attributes it finds.

So if you want to create a number of buttons your could do

this.makeUI = function(container)
{
    self.buttons.push({
        text: "button " + self.buttons().length,
        handler: this.hello
    });
}

Here's a fiddle.

http://jsfiddle.net/madcapnmckay/ACjvs/

Hope this helps.

like image 170
madcapnmckay Avatar answered Oct 26 '22 16:10

madcapnmckay