6

我以前使用过 Knockout 模板,所以我不确定为什么这对我不起作用。我尝试了两种不同风格的 ko 标记,都不起作用。

<!-- more nesting levels -->
<div class="cal-day-tps" data-bind="foreach: timePeriods">
    <div class="cal-day-tp-cont">

        <div data-bind="template: { name: 'tp-ed-templ', data: $data }"></div>

        //both of these methods fail
        <!-- ko template: { name: 'tp-ed-templ', data: $data } -->
        <!-- /ko -->

    </div>
</div>    
<!-- /more nesting levels -->


<script type="text/html" id="tp-ed-templ">
 <!-- bunch of markup -->
</script>

我只是收到错误“找不到 ID 为 tp-ed-templ 的模板”。

可能只是一个错字,但我一直没能找到它。

这似乎是 Durandal 的问题,而不是 Knockout

我在 vanilla durandal 设置中尝试了一些非常简单的案例,它仍然做同样的事情。甚至尝试将脚本放在与绑定相同的嵌套位置,没有骰子。

4

2 回答 2

10

简短的回答:您目前不能Durandal 中使用 Knockout 模板。但是,正如nemesv指出的那样,如果您将命名模板放在 Durandal 之外,ko 能够找到它们。例如,<div id="applicationHost"></div>元素之外的任何地方。

其他解决方法是使用 Durandal 的撰写功能,或者只是将模板内联为匿名。

在不久的将来可能会支持淘汰模板。

我终于在 Durandal 谷歌小组中找到了这些答案,

于 2013-03-28T19:40:21.997 回答
3

问题是在绑定 Durandal 视图之前DOM 中必须存在KO 模板元素。这是因为视图在插入 DOM之前已绑定,因此任何包含的模板都无法通过 ID 解析。

使用返回observable的函数可用于稍后重新触发模板绑定 .. 它可以工作,但很不稳定。(绑定可以用于类似的效果。)if

// bind to this in markup:
//   <div data-bind="template: {name: $root.templateName, .. }">
vm.templateName = function () {
   return vm.TemplateId();
};

// Changing this will trigger an observable in the KO template binding;
// don't ask me why we have to pass in a function to 'name' ..
vm.TemplateId = ko.observable("dummy-template-id-that-exists");

// After the view is attached the correct template element is in the DOM
// so we can trigger the template to (re-)bind and it will find it.
function viewAttached () {
   vm.TemplateId("the-real-template-id");
}
于 2013-05-22T23:49:08.743 回答