6

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.

Community
  • 1
  • 1
BlaShadow
  • 11,075
  • 7
  • 39
  • 60

1 Answers1

11

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.

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
madcapnmckay
  • 15,782
  • 6
  • 61
  • 78
  • 1
    I tried the fiddle above with your solution, but it does not work anymore. Any idea? – guido May 09 '14 at 15:22
  • 2
    The knockout.js link in the jsfiddles no longer works. I updated them to point at a CDN mirror. Try; http://jsfiddle.net/ACjvs/75/ http://jsfiddle.net/qSqJv/84/ – MrTrick Sep 03 '14 at 02:27