gpt4 book ai didi

knockout.js - 从 knockout 3.2 中的自定义组件更新 observable

转载 作者:行者123 更新时间:2023-12-01 08:28:57 25 4
gpt4 key购买 nike

我正在尝试使用 knockout 3.2 中的自定义组件并从组件内更新可观察对象。这是我的自定义组件的示例:

ko.components.register('voting', {
viewModel: function(params) {
var self = this;
this.votes = params.votes;
this.yourVote = params.yourVote;

this.callback = function(num){
self.yourVote(parseInt(num)); // here I am updating
self.votes( self.votes() + parseInt(num) );
};
},
template: { element: 'voting-tpl' }
});

它的模板如下所示:
<voting params="votes: votes(), yourVote: yourVote()"></voting>
<template id="voting-tpl">
<div data-bind="click:function(){callback(1)}">Up</div>
<div data-bind="text: votes"></div>
<div data-bind="click:function(){callback(-1)}">Down</div>
</template>

问题是,当我 click on Up/Down function in my full JS fiddle .我得到

Uncaught Error: Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.



当然,我可以使用 var a = new Vm(); 并使用 a.yourVote(num); 从组件内部更新它,但这破坏了组件的整体思路。

我怎样才能正确地做到这一点?

最佳答案

您应该将 observable 作为参数传递给自定义组件,而不是创建依赖项:

<voting params="votes: votes, yourVote: yourVote"></voting>     

您可以在此处阅读更多 knockout 3.2 components(如何将参数传递给组件)

The params are provided to initialize the component, like in the component binding, but with a couple of differences:

  • If a parameter creates dependencies itself (accesses the value of an observable or computed), then the component will receive a computed that returns the value. This helps to ensure that the entire component does not need to be rebuilt on parameter changes. The component itself can control how it accesses and handles any dependencies.


Fixed JSFiddle DEMO

关于knockout.js - 从 knockout 3.2 中的自定义组件更新 observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25845317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com