我正在尝试使用knockout将小部件数组绑定到自定义模板。
基本上每个小部件都定义了templateToUse。
但是当我尝试将每个小部件绑定到模板并调用getTemplate
函数时,我得到undefined
错误。
我还设置了一个名为afterRender的函数,它抛出了这个错误:Error: Unable to get property 'nodeType' of undefined or null reference
。
我做错了什么?
HTML:
<div class="row" data-bind="template: { name: getTemplate, foreach: { data: widgets, afterRender: $root.afterAddWidget }}">
</div>
<script type="text/html" id="panel-template">
<div class="panel panel-color" data-bind="css: $data.panelType" id="demo-panel-network">
<div class="panel-heading">
<h3 class="panel-title">Green colored panel</h3>
<div class="panel-control">
<button class="btn" id="demo-panel-network-refresh" data-toggle="panel-overlay" data-target="#demo-panel-network"><i class="fa fa-refresh"></i></button>
<div class="btn-group">
<button class="btn btn-default" data-toggle="dropdown"><i class="fa fa-gear"></i></button>
<ul class="dropdown-menu dropdown-menu-right">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</div>
<button class="btn btn-default" data-toggle="panel"><i class="fa fa-chevron-down"></i></button>
<button class="btn btn-default" data-bind="click: $root.delete_widget"><i class="fa fa-times"></i></button>
</div>
</div>
<div class="panel-body">
<p>fdgd</p>
</div>
</div>
</script>
JS:
$(function () {
var ViewModel = function (widgets) {
this.widgets = ko.observableArray(widgets);
this.delete_widget = function (item) {
self.widgets.remove(item);
};
this.getTemplate = function (item) {
alert(item.templateToUse);
return item.templateToUse;
}
this.afterAddWidget = function (items) {
alert('after');
};
};
var widgets = [
{ x: 0, y: 0, width: 6, height: 6, noResize: 'yes', noMove: 'no', autoposition: 'no', isLocked: 'no', panelType: 'panel-success', templateToUse: 'panel-template' },
{ x: 8, y: 0, width: 4, height: 2, noResize: 'yes', noMove: 'no', autoposition: 'no', isLocked: 'no', panelType: 'panel-warning', templateToUse: 'panel-template' },
{ x: 0, y: 8, width: 4, height: 2, noResize: 'yes', noMove: 'no', autoposition: 'no', isLocked: 'no', panelType: 'panel-info', templateToUse: 'panel-template' },
{ x: 4, y: 8, width: 4, height: 2, noResize: 'yes', noMove: 'no', autoposition: 'no', isLocked: 'no', panelType: 'panel-danger', templateToUse: 'panel-template' },
{ x: 8, y: 8, width: 4, height: 2, noResize: 'yes', noMove: 'no', autoposition: 'no', isLocked: 'no', panelType: 'panel-purple', templateToUse: 'panel-template' },
];
var viewModel = new ViewModel(widgets);
ko.applyBindings(viewModel);
});
答案 0 :(得分:0)
您的foreach
放错了地方。您想绑定小部件的模板foreach。
<div class="row" data-bind="template: { name: getTemplate,
foreach: widgets,
afterRender: $root.afterAddWidget }"></div>
你设置它的方式,你告诉knockout将你的映射渲染为模板的项目。