2011-11-16 108 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