2013-03-28 26 views
6

我之前使用過Knockout模板,所以我不確定爲什麼這不適合我。 我嘗試了兩種不同風格的ko標記,都沒有工作。KO找不到ID爲的模板

<!-- 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模板」。

可能只是一個錯字,但我一直無法找到它。

這似乎是一個迪朗達爾問題,而不是淘汰賽

我嘗試了一些非常簡單的香草迪蘭戴爾設置案例,它仍然做同樣的事情。甚至試圖將腳本放在與綁定相同的嵌套位置,而不是骰子。

+0

哪裏是你的'ko.applyBindings()'被稱爲? – jmoerdyk

+0

是的,我們可以看到更多的代碼嗎?的jsfiddle? – woz

+0

我不能看到更多的代碼,我能想到的唯一的事情就是在整個DOM被加載並準備好之前調用綁定。 – jmoerdyk

回答

10

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

其他解決方法是使用Durandal的撰寫功能,或者只是將模板內聯爲匿名。

在不久的將來可能會支持淘汰模板。

我終於挖出這些答案上來就迪朗達爾谷歌組,

+1

如果您將Durandal以外的命名模板添加到index.cstml中,它將起作用,KO可以在其中找到它。 – nemesv

+1

有趣的是,這確實有效。謝謝! –

+0

我在早期就有同樣的問題,並建議仔細研究使用Durandal的ko.compose綁定來完成我的任務。我發現ko.compose可以滿足我大部分的模板需求,並且可以非常順暢地與Durandal一起工作。你可以指定一個模板名稱(我認爲Durandal認爲它是一個區域名稱),合成引擎將加載html並將其綁定到當前模型。 –

2

的問題是,KO模板元素必須在DOM之前就存在的杜蘭達爾的觀點是有約束力的。這是因爲視圖在之前被綁定到之前,因此它被插入到DOM中,因此任何包含的模板都無法通過ID解析。

使用功能返回一個觀察到可用於以後再次觸發模板結合..它的工作原理,但靠不住的。 (安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"); 
}