Updating observables from custom components in knockout 3.2

I am trying to use custom components from knockout 3.2 and update observables from within the component. Here's an example of my custom component:

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' }


The template for it looks like this:

<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>


The problem is when I click on the Up / Down function in my full JS script . I get

Unprepared error: Cannot write ko.computed value unless you specify the "write" option. If you want to read the current value, don't pass any parameters.

Of course, I can use var a = new Vm();

and update it from within a component with help a.yourVote(num);

, but that breaks the whole idea of ​​components.

How can I make it right?


source to share

1 answer

You should pass your observables as parameters to the custom component instead of creating dependencies:

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


You can read more about knockout components 3.2 here (How to pass parameters to a component)

A parameter is provided to initialize a component, just like in component binding, but with a few differences:

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

Fixed JSFiddle DEMO



All Articles