如何使用基因剔除绑定新元素? [英] How do I bind new elements using knockout?

查看:84
本文介绍了如何使用基因剔除绑定新元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我有这样的东西

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

但根据这些 推荐答案

基因剔除的目标是仅对一组dom元素调用基因剔除一次.因此,如果您在整个文档上重复调用applyBindings,则会遇到多个绑定的问题.

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.

在某些情况下,多次调用applyBindings是合理的,在部分视图中,这种情况在第一次绑定时不在dom中,因此没有绑定.您可以通过选择性地将applyBindings限定到该dom元素来绑定这些对象.

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.

如果要动态创建dom元素并通过敲除使其绑定,最常用的方法是使用内置的模板功能,该功能可以插入元素并绑定找到的任何数据绑定属性.

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

这是小提琴.

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

希望这会有所帮助.

这篇关于如何使用基因剔除绑定新元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆