【问题标题】:KnockoutJS dynamic templatesKnockoutJS 动态模板
【发布时间】:2013-04-05 21:24:01
【问题描述】:

如果有人问过这个特定问题,请原谅。我搜索了博客、线程以搜索此内容,但找不到任何符合我需求的内容。

我正在尝试使用 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) { ... }" />

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

【问题讨论】:

  • 点击处理程序在哪里定义并绑定到 button1。
  • 我更新了我原来的问题来回答你的问题,谢谢。

标签: knockout.js


【解决方案1】:

如果您的目标是使用单个 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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 2012-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多