Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to pass variables with custom components in knockout 3.2

I am trying to move forward with custom components in knockout 3.2. Everything works nice if I am using predefined parameters. For example is this jsFiddle.

But when I pass parameters from my view model (I have read how to do it here) I am not getting anything: jsFiddle. What am I doing wrong?

Here is my js code:

ko.components.register('pagination', {
    viewModel: function (params) {
        var self = this;
        this.page = ko.observable(params.page);
        this.max = ko.observable(params.max);

        this.list = ko.pureComputed(function () {
            var a = self.page(),
                list = [],
                min = a - 2 < 1 ? 1 : a - 2,
                max = a + 2 > self.max() ? self.max() : a + 2;

            for (var i = min; i <= max; i++) {
                list.push(i);
            }
            return ko.observableArray(list);
        });

        this.callback = function (i) {
            console.log(i);
            self.page(i);
        };
    },
    template: {
        element: 'pagination-tpl'
    }
});

function Vm(){
    this.page = ko.observable(2);
    this.max = ko.observable(6);
}
var vm = new Vm();

ko.applyBindings(vm, document.getElementById('koBinding_somePage'));
like image 373
Salvador Dali Avatar asked Mar 19 '23 14:03

Salvador Dali


1 Answers

The linked article explains this behavior int he How params are passed to the component section:

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.

So in your case the params.page and the params.max contain a computed observable property and not the value.

So you just need to assign them to your local fields:

viewModel: function (params) {
       var self = this;
       this.page = params.page;
       this.max = params.max;
       //...
}

Demo JSFiddle.

like image 62
nemesv Avatar answered Apr 30 '23 04:04

nemesv