如何使用Knockout绑定注入jQuery模板

时间:2013-11-04 12:01:19

标签: knockout.js jquery-templates

首先,我有一个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中激活一个Alert:

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/

2 个答案:

答案 0 :(得分:1)

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

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

JSFiddle DEMO

答案 1 :(得分:0)

如果没有更广泛地理解你试图解决的问题的背景,我可能会咆哮错误的树。但是,我怀疑你是以错误的方式解决问题。您永远不需要重复将模板添加到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>

我还应该指出,我已经用CSS类替换了容器的id,因为这更有意义。