6

页面加载后如何绑定新元素创建?

我有这样的东西

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);

如果我试试这个

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

但根据这些 帖子,它不会起作用。

4

1 回答 1

11

淘汰赛的目标是只在一组 dom 元素上调用一次淘汰赛。因此,如果您在整个文档上重复调用 applyBindings,您将遇到多个绑定的问题。

在某些情况下,多次调用 applyBindings 是合理的,这是在第一次绑定时不在 dom 中的局部视图的情况下,因此未绑定。您可以通过有选择地将 applyBindings 限定到该 dom 元素来绑定它们。

这是您尝试实现的目标的示例。您的问题是您没有插入您创建的节点。

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

对于这个特定的例子,我不会推荐这种方法,有更好的方法。

如果您想动态创建 dom 元素并通过敲除绑定它们,最常见的方法是使用内置的模板功能,该功能负责插入元素并绑定它找到的任何数据绑定属性。

因此,如果您想创建许多按钮,您可以这样做

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

这是一个小提琴。

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

希望这可以帮助。

于 2012-04-07T05:17:00.823 回答