【问题标题】:How to inject jQuery Template with Knockout bindings如何使用 Knockout 绑定注入 jQuery 模板
【发布时间】:2013-11-15 01:08:45
【问题描述】:

首先,我有一个 Button addTemplate,它将通过 Knockout 和 jQuery 将 html 添加到我的正文中:

<button data-bind="click: addTemplate">Add Template</button>

<script type="text/html" id="MyTemplate">
    <div id="container">
        <a href="#" data-bind="click: $root.doAlert">Do Alert</a>
    </div>
</script>

添加的模板也有一些淘汰赛绑定。他们应该在我的 ViewModel 中激活警报:

function MyViewModel()
{
    self = this;

    self.addTemplate = function () {
        $($("#MyTemplate").html()).appendTo("body");
    }

    self.doAlert = function() {
        alert('Hello World');
    } 
}

ko.applyBindings(new MyViewModel());

当我点击我添加的模板中的链接时,doAlert 函数什么也不做。 我不想在我的 ViewModel 中使用字符串链接的 HTML 模板。

这里是小提琴:http://jsfiddle.net/tgu8C/5/

【问题讨论】:

标签: knockout.js jquery-templates


【解决方案1】:

如果不对您要解决的问题的背景有更广泛的了解,我可能会找错树。但是,我怀疑您以错误的方式解决问题。您永远不需要重复将模板添加到 DOM。按照预期使用Knockout templates 将为您执行此操作。我可以建议以下模型...

function MyViewModel() {
    var self = this;

    self.items = ko.observableArray([]);

    self.add = function () {
        self.items.push({});
    };

    self.doAlert = function() {
        alert('Hello World');
    } 
}

ko.applyBindings(new MyViewModel());

...伴随着以下标记...

<button data-bind="click: add">Add Template</button>
<!-- ko template: { name: 'myTemplate', foreach: items } -->
<!-- /ko -->
<script type="text/html" id="myTemplate">
    <div class="container">
        <a href="#" data-bind="click: $root.doAlert">Do Alert</a>
    </div>
</script>

我还应该指出,我已将 container 的 id 替换为 CSS 类,因为这样更有意义。

【讨论】:

    【解决方案2】:

    您应该对新添加的元素应用绑定。

    var newElement = $($("#MyTemplate").html()).appendTo("body");
    ko.applyBindings(self, newElement);  
    

    JSFiddle DEMO

    【讨论】:

      猜你喜欢
      • 2015-01-19
      • 1970-01-01
      • 2013-03-11
      • 2013-10-09
      • 2015-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-01
      相关资源
      最近更新 更多