1

如果有人问过这个特定的问题,请原谅。我搜索了博客,搜索了这个,但找不到任何特别符合我需求的东西。

我正在尝试使用 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。似乎没有办法做到这一点,没有另一个 3rd 方添加?

更新 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'作为这么多帖子,线程状态,还有另一种方法可以做到这一点吗?我对这一切都很陌生,所以如果我的方法看起来很愚蠢,请原谅。

我已经看到线程指出单击事件应由 Knockout 处理:

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

但这让我回到了最初的问题,如何加载第二个模板,在单击按钮时绑定到它。

4

1 回答 1

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

因此,您将模板的名称存储在可观察对象中并对其进行更新。示例: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/

于 2013-04-05T13:24:01.107 回答