简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM