我正在尝试使用knockout.js构建基于jquery的树查看器库(https://github.com/davewood/treejo)
我构建了一个组件,并希望在自己的模板中使用该组件。
几乎正常工作但是当嵌套组件初始化时我得到了奇怪的错误。
如果您打开控制台,此JSFiddle会演示此问题。 http://jsfiddle.net/tyx89ude/8/
我必须将knockout.js复制并粘贴到javascript窗口中(向下滚动以查看我的代码),因为如果我通过jsfiddle加载了knockout,那么ko.components函数就不可用了。
ko.components.register('node', {
viewModel: function (params) {
console.log(params);
var self = this;
self.title = ko.observable(params.title);
self.url = params.url;
self.body = ko.observable(params.body);
self.classes = ko.observable('node node-closed');
self.children = ko.observableArray(params.children);
self.load = function () {
var data1 = {
'title': "title1",
'body': "body1",
'url': "url1"
};
var data2 = {
'title': "title2",
'body': "body2",
'url': "url2"
};
self.children.push(data1);
self.children.push(data2);
self.classes('node node-open');
};
self.children.subscribe(function (data) {
console.log(data)
});
},
template:
'<div data-bind="css: classes">\
<div class="node-panel">\
<div class="node-heading">\
<a class="node-toggle" data-bind="click: load">></a>\
<span class="node-title" data-bind="text: title"></span>\
</div>\
<!-- ko if: body -->\
<div class="node-body" data-bind="text: body"></div>\
<!-- /ko -->\
</div>\
<div class="node-content" data-bind="if: children().length > 0">\
<div data-bind="attr: { title: title }" class="node-closer"><div></div></div>\
<div data-bind="foreach: { data: children(), as: \'child\' }"></div>\
<div data-bind="component: { name: \'node\', params: child }"></div>\
</div>\
</div>\
</div>'
});
更新:正确的JSFiddle。 http://jsfiddle.net/tyx89ude/26/谢谢弗拉德
答案 0 :(得分:2)
您的模板标记错误
变化:
<div data-bind="foreach: { data: children(), as: \'child\' }"></div>\
要
<div data-bind="foreach: { data: children(), as: \'child\' }">\