在绑定处理程序的帮助下,我终于能够拼凑出一个惰性模板加载器。想分享。
懒加载器
markupLoader = {
templateDictionary: {},
loadMarkup: function (element, value, bindingContext) {
if (!this.templateDictionary[value]) {
this.templateDictionary[value] = $.get(value);
}
this.templateDictionary[value].done(function (template) {
$(element).html(template);
$(element).children().each(function (index, child) {
ko.applyBindings(bindingContext, child);
});
});
}
};
绑定处理程序
ko.bindingHandlers.htmlUrl = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
let value = ko.unwrap(valueAccessor());
markupLoader.loadMarkup(element, value, bindingContext);
return { controlsDescendantBindings: true };
}
};