当我们将 KO 组件作为参数传递时,它会接收到 observable 的引用。当组件接收它作为参考时,您可以写入此可观察对象,它将反映在您的视图模型上;但是,当您使用 ko-es5 插件(超级棒)时,您的 KO 组件而不是接收也对您的 observable 的引用会接收某种 computeObservable,我们无法写入它。这是意外的行为吗?
仅使用淘汰赛尝试
http://jsfiddle.net/kapuca/k0fw8w18/
<voting params="votes: votes"></voting>
<template id="voting-tpl">
<button data-bind="click: increment ">Up</button>
<div data-bind="text: votes"></div>
</template>
ko.components.register('voting', {
viewModel: function(params) {
var self = this;
self.votes = params.votes;
self.increment = function(){
self.votes( self.votes() + 1 );
};
return self;
},
template: { element: 'voting-tpl' }
});
function Vm(){
this.votes = ko.observable(5);
return this;
}
ko.applyBindings(new Vm() );
尝试使用敲除 + ko-es5 插件
http://jsfiddle.net/kapuca/jwea6zaL/
<voting params="votes: votes"></voting>
<template id="voting-tpl">
<button data-bind="click: increment ">Up</button>
<div data-bind="text: votes"></div>
</template>
ko.components.register('voting', {
viewModel: function(params) {
var self = this;
self.votes = params.votes;
self.increment = function(){
self.votes( self.votes + 1 );
};
return ko.track(self);
},
template: { element: 'voting-tpl' }
});
function Vm(){
this.votes = 5;
return ko.track(this);
}
ko.applyBindings(new Vm() );