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

标签 knockout.js knockout-3.0 knockout-components

我正在尝试使用 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/

相关文章:

javascript - 表数据不使用 ko.js mvc 显示为 html

javascript - 绑定(bind)多维knockoutjs observableArray

javascript - 以编程方式更新可观察值时 Knockoutjs 不更新 UI

javascript - 如何从主 ViewModel 更新组件内的可观察数组?

javascript - knockout foreach 绑定(bind)不起作用

javascript - 在 knockout 组件中丢失上下文

knockout.js - 使用从服务器接收的 JSON 数据更新 View 模型时刷新 Knockout 绑定(bind)

knockout.js - Knockout 组件 - 跨组件传递值

javascript - Knockout Components ,模板已经注入(inject)到该元素中,但尚未绑定(bind)

javascript - 为什么使用 Knockout.js 时数据没有出现在 HTML 字段中