2011-11-16 136 views
1

我目前使用ExternalTemplate擴展來在運行時通過ajax加載我的模板。不過,我期望稍微擴展這個功能,這樣我可以提供多個模板目錄。如何將自定義數據綁定添加到knockoutjs的模板綁定中

我知道這似乎有點奇怪,但我有幾個地方模板可能來自,不可能讓他們都不幸從一個大模板文件夾出來。

我希望做一些事情,如:

<script type="text/javascript"> 
var templateEngineSettings = { 
    templatesLocations: { 
     "default":"/view-templates-1" 
     "other1":"/view-templates-2" 
     "other2":"/somewhere-else/view-templates" 
    }, 
    templateSuffix: ".template.html" 
}; 

ko.externaljQueryTemplateEngine.setOptions(templateEngineSettings); 
</script> 

<div data-bind="template: {name: 'some-template', location:'default'}"></div> 
<div data-bind="template: {name: 'some-other-template', location:'other1'}"></div> 
<div data-bind="template: {name: 'some-new-template', location:'other3'}"></div> 

但是我無法找到如何做到這一點的任何固體文檔,所以任何幫助將是巨大的!

ko.ExternalTemplateEngine.templateUrl

一種選擇是創建一個包裝的模板結合,將您的模板位置互換這個值:

回答

1

外部模板引擎從拉其網址基地。例如:

//custom binding 
ko.bindingHandlers.templatex = { 
    update: function(element, valueAccessor, allBindingsAccessor, viewModel) { 
     var options = valueAccessor(), 
      location = options.location, 
      current = koExternalTemplateEngine.templateUrl; 

     //set to our new location 
     ko.ExternalTemplateEngine.templateUrl = ko.bindingHandlers.templatex.templateLocations[location]; 

     //call the real template binding 
     ko.bindingHandlers.update.tempate(element, valueAccessor, allBindingsAccessor, viewModel); 

     //reset the location back to the default 
     ko.ExternalTemplateEngine.templateUrl = current; 
    }, 
    templateLocations: {} 
}; 

//set in your app code 
ko.bindingHandlers.templatex.templateLocations = { 
    "default":"/view-templates-1", 
    "other1":"/view-templates-2", 
    "other2":"/somewhere-else/view-templates" 
}; 
+0

感謝您的信息,稍後我會回家的時候會更加深入。如果可以的話,我打算創建外部模板代碼的一個可能的分支來支持多個模板,但如果所有更改都在一個地方而不是2個,那麼這可能是一個更好的方法(knockoujs擴展,自定義外部模板構建) – Grofit

相關問題