KnockoutJS动态模板

时间:2013-04-05 06:27:23

标签: knockout.js

请原谅这个特殊问题是否有问题。我搜索了博客,搜索了这个但是找不到任何特别符合我需求的东西。

我正在尝试使用Knockout JS构建一个单页面应用程序,而我对此相对较新,似乎无法解决这个问题。

我有两个模板:

<script id="template1" type="text/template">
   <h3>Template 1</h3>
   <button id="templButton" text="Go to template 2" />
</script>

<script id="template2" type="text/template">
   <h3>Template 2</h3>
</script>

我有两个与这些模板绑定的div:

<div data-bind="template: { name: template1 }"></div>
<div data-bind="template: { name: template2 }"></div>

在模板1中,我有一个按钮,当点击时,应该填充模板2并清除模板1.似乎没有办法做到这一点,没有另外的第三方添加?

更新1

在页面加载时,我使用jQuery获取第一个模板的值:

$(document).ready(function(e) {
   $.get("/Controller/Action", function (data) {

       // get values from action, convert to array for ko to function
       var results = $.parseJSON(data);
       var viewModel = {
          someBind = ko.mapping.fromJS(results);
       }
       ko.applyBindings(viewModel);

       // now, I thought the best way to do this was to bind to the button here:
       $("#templButton").click(function(e) {
          // and call the load of the template here,
          // however, because I have two templates on the page
          // Knockout is trying to bind to both.
       });
   });
});

没有使用'templateToUse'那么多帖子,线程状态,是否还有其他方法可以做到这一点?我对这一切都很陌生,所以请原谅我的做法是否愚蠢。

我见过线程声明click事件应该由Knockout处理:

<button data-bind="click: function(e) { ... }" />

但这让我回到原来的问题,如何加载第二个模板,点击按钮时绑定到它。

1 个答案:

答案 0 :(得分:10)

如果您的目标是使用单个div进行此操作,那么可以采用以下方法:

<script id="template1" type="text/template">
   <h3>Template 1</h3>
   <button id="templButton" data-bind="click: swap">Go to template 2</button>
</script>

<script id="template2" type="text/template">
   <h3>Template 2</h3>
</script>

<div data-bind="template: theTemplate"></div>

使用视图模型:

ko.applyBindings({
    theTemplate: ko.observable("template1"),
    swap: function() {
       this.theTemplate("template2");   
    }
});

因此,您将模板的名称存储在一个observable中并进行更新。示例:http://jsfiddle.net/rniemeyer/SfaPH/

如果你真的想在两个div中想要这个,那么你需要有一个标志来说明哪一个被渲染或可见:

绑定它:

<div data-bind="template: { name: 'template1', 'if': one }"></div>
<div data-bind="template: { name: 'template2', ifnot: one }"></div>

使用视图模型:

ko.applyBindings({
    one: ko.observable(true),
    swap: function() {
       this.one(false);
    }
});

示例:http://jsfiddle.net/rniemeyer/n2y6z/

相关问题