我使用Knockout组件和System.js进行模块加载。
我有一个自定义组件加载器:
var myComponentLoader = {
loadComponent: function(name, componentConfig, callback) {
System.import(componentConfig.myLoader)
.then(function(loadedComponent) {
var result = {
template: ko.utils.parseHtmlFragment(loadedComponent.componentTemplate),
createViewModel: loadedComponent.MyComponentViewModel
}
callback(result);
})
// .catch(function(myError){
// alert(myError);
// callback(null);
// });
}
};
// Register it
ko.components.loaders.unshift(myComponentLoader);
ko.components.register('my-component', { myLoader: './app/components/components' });
但是这失败了以下消息:
TypeError:undefined不是函数{stack:(...),message:" undefined不是函数"}
这就是我的result.template的样子:
<div>This is my component template</div>
<div data-bind="text: myName"></div>
这就是我的result.createViewModel的样子:
function MyComponentViewModel(params) {
// Set up properties, etc.
this.myName = ko.observable("Amy Smith");
this.doSomething(params);
this.boundAt = ko.observable(moment().format());
}
以下是完整错误:
Potentially unhandled rejection [1] TypeError: undefined is not a function
at Object.ko.utils.cloneNodes (http://localhost:8081/lib/bower/knockout@3.3.0/dist/knockout.js:270:48)
at cloneTemplateIntoElement (http://localhost:8081/lib/bower/knockout@3.3.0/dist/knockout.js:3644:41)
at null.callback (http://localhost:8081/lib/bower/knockout@3.3.0/dist/knockout.js:3621:21)
at Function.ko_subscribable_fn.notifySubscribers (http://localhost:8081/lib/bower/knockout@3.3.0/dist/knockout.js:1103:38)
at http://localhost:8081/lib/bower/knockout@3.3.0/dist/knockout.js:3151:54
at http://localhost:8081/lib/bower/knockout@3.3.0/dist/knockout.js:3169:21
at http://localhost:8081/lib/bower/knockout@3.3.0/dist/knockout.js:3198:29
at eval (http://localhost:8081/app/components/components-bootstrapper.js!eval:32:13)
at O (http://localhost:8081/lib/es6-module-loader.js:7:7439)
at K (http://localhost:8081/lib/es6-module-loader.js:7:7071)
答案 0 :(得分:3)
要提供自定义配置处理逻辑,您需要实现documentation中所述的loadComponent
方法。
但是你需要注意从中返回的内容,因为根据文档:
template
属性必须包含 DOM节点数组:所以如果你的加载器加载了一个字符串,你需要首先解析它:
template: ko.utils.parseHtmlFragment(loadedComponent.componentTemplate)
createViewModel
必须包含工厂函数,因此不能直接使用您的视图模型构造函数。所以你需要用
createViewModel: function (params, componentInfo) { return new loadedComponent.viewModel(params, componentInfo); }