gpt4 book ai didi

javascript - 如何在使用组件时定义模板 url

转载 作者:行者123 更新时间:2023-11-30 09:49:19 24 4
gpt4 key购买 nike

我正在使用 knockout 组件,但我想使用模板 url 而不是内联模板。这是我正在使用的组件:

ko.components.register('cat-data', {
viewModel: {
createViewModel: function(params, componentInfo) {
var self = this;

self.data = (params && params.data) || [];

return self;
}
},
template: "/Scripts/CatdDataTemplate.html"
});

当我运行此 /Scripts/CatdDataTemplate.html 时,显示的不是实际模板。

最佳答案

作为字符串的模板属性将被 knockout 解析为要应用的实际模板。如果你想从 url 加载模板,你可以使用自定义加载器来实现,如 knockout documentation 中定义的那样,引用如下:

If your custom loader implements loadTemplate and/or loadViewModel, then you can plug in custom code to the loading process. You can also use these functions to interpret custom configuration formats.

For example, you might want to enable configuration formats like the following:

ko.components.register('my-component', {
template: { fromUrl: 'file.html', maxCacheAge: 1234 },
viewModel: { viaLoader: '/path/myvm.js' }
});

… and you can do so using custom loaders.

The following custom loader will take care of loading templates configured with a fromUrl value:

var templateFromUrlLoader = {
loadTemplate: function(name, templateConfig, callback) {
if (templateConfig.fromUrl) {
// Uses jQuery's ajax facility to load the markup from a file
var fullUrl = '/templates/' + templateConfig.fromUrl + '?cacheAge=' + templateConfig.maxCacheAge;
$.get(fullUrl, function(markupString) {
// We need an array of DOM nodes, not a string.
// We can use the default loader to convert to the
// required format.
ko.components.defaultLoader.loadTemplate(name, markupString, callback);
});
} else {
// Unrecognized config format. Let another loader handle it.
callback(null);
}
} }; // Register it ko.components.loaders.unshift(templateFromUrlLoader);

来源:http://knockoutjs.com/documentation/component-loaders.html#example-2-a-component-loader-that-loads-external-files-using-custom-code

关于javascript - 如何在使用组件时定义模板 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37261699/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com