我有以下组件:
<template id="fruits-tpl">
<p>Name: <input data-bind="value: name" /></p>
<p>Type: <input data-bind="value: color" /></p>
</template>
ko.components.register('fruits', {
viewModel: function(params) {
this.name = params.name;
this.color = params.color;
},
template: { element: 'fruits-tpl' }
});
我将此组件与下面的视图模型一起使用,其中可观察列表中的项目具有不同的类型并具有不同的属性:
function Fruit(data) {
this.name = ko.observable(data.name);
this.color = ko.observable(data.color);
}
function Dessert(data) {
this.name = ko.observable(data.name);
this.packaging = ko.observable(data.packaging);
}
function Vm(){
var data = [{name:"Apples",color:"Yellow"},{name:"Cookies",packaging:"Box"}];
this.items = ko.observableArray([new Fruit(data[0]),new Dessert(data[1])]);
this.items.choice = ko.observable(this.items()[0]);
}
该组件运行良好,每次更改输入框中的文本时都会更新基础数据:
<div data-bind="component: {name: 'fruits', params: items.choice}"></div>
现在,我想将我的 observables 的逻辑封装到组件本身中,所以我以这种方式更改了组件:
ko.components.register('fruits', {
viewModel: function(params) {
this.name = ko.observable(params.name);
this.color = ko.observable(params.color);
},
template: { element: 'fruits-tpl' }
});
...现在我有了可观察的 items.choice,里面只有数据:
function Vm(){
var data = [{name:"Apples",color:"Yellow"},{name:"Cookies",packaging:"Box"}];
this.items = ko.observableArray(data);
this.items.choice = ko.observable(this.items()[0]);
}
为什么在我的第二个示例中没有更新主视图模型中的基础数据,尽管 items.choice 仍然是可观察的?我确定我错过了一些概念,也许我的可观察数组中的每个项目也应该是可观察的,但我不明白是否有办法让第二个例子工作。
第一个例子:http: //jsfiddle.net/5739ht0q/2/ 第二个例子:http: //jsfiddle.net/079tx0nn/