在下面的示例中,我试图根据迭代数据中的字段呈现几个组件中的一个。我已经定义了这些模板:
<template id="select-template">
<select data-bind="style: {width: size}, value: value, options: options, optionsText: 'optTxt', optionsValue: 'optId'"></select>
</template>
<template id="input-template">
<!--input type="text" data-bind="style: {width: size}, value: value" /-->
<input type="text" data-bind="value: 'input'" />
</template>
<template id="mu-template">
<span data-bind="text: value"></span>
</template>
并注册了这些对应的组件:
ko.components.register('input', {
viewModel: InputModel,
template: {
element: 'input-template'
}
});
ko.components.register('select', {
viewModel: InputModel,
template: {
element: 'select-template'
}
});
ko.components.register('mu', {
viewModel: InputModel,
template: {
element: 'mu-template'
}
});
它们都使用的视图模型构造函数是:
function InputModel(params) {
if (!('id' in params)) {
throw "Model broke";
}
var keys = ['id', 'size', 'value', 'options'];
for (var i=0; i<keys.length; ++i) {
var k = keys[i];
if (k in params) {
this[k] = params[k];
}
}
console.debug("Model:", [this]);
}
我有两个问题:
- 当选择模板正在渲染,我得到一个错误说
Multiple bindings (options and component) are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.
- 可能相关,如果我在
InputModel
中不做错误检查/抛出,它会在没有参数的无限循环中被调用。
这是怎么回事?
http://jsfiddle.net/6srq9yfc/问题是您正在用现有DOM元素的名称注册您的组件:input
, select
。
<select data-bind="style: {width: size},
value: value, options: options,
optionsText: 'optTxt', optionsValue: 'optId'"></select>`
作为组件,它与options
绑定发生冲突,并得到错误消息。
您可以通过将组件重命名为不存在的DOM元素来轻松解决此问题:
ko.components.register('my-input', {
viewModel: InputModel,
template: {
element: 'input-template'
}
});
ko.components.register('my-select', {
viewModel: InputModel,
template: {
element: 'select-template'
}
});
演示JSFiddle。