如何添加自定义数据绑定到knockoutjs'模板绑定

How do I add custom data-bindings to knockoutjs' template binding

本文关键字:knockoutjs 绑定 数据绑定 何添加 添加 自定义      更新时间:2023-09-26

我目前正在使用ExternalTemplate扩展在运行时通过ajax加载我的模板。然而,我希望稍微扩展这个功能,这样我就可以提供多个模板目录。

我知道这看起来有点奇怪,但是我有几个模板可以来自的地方,不幸的是,不可能把它们都从一个大的模板文件夹中取出来。

我希望这样做:

<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

一种选择是为模板绑定创建一个包装器,该包装器将从模板位置交换该值。比如:

//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"
};