Knockoutjs computed passing parameters

前端 未结 4 2054
终归单人心
终归单人心 2021-01-31 15:01

I am wondering if it is possible with knockoutjs to pass arguments when binding.

I am binding a list of checkboxes and would like to bind to a single computed observabl

4条回答
  •  故里飘歌
    2021-01-31 15:40

    The accepted answer is decent, but if you have a function that generates a ko.computed for each checkbox, you are adding unnecessary overhead with multiple anonymous computed observables, which adds up quickly when your checkbox lists exceed 4-5 options.

    This is a simpler implementation of a bitwise scenario, but the computed function can be whatever need be.

    
    
    
    
    
    
    
    
    

    Script:

    var vm = function() {
        var vm = this;
    
        this.checkedList = ko.observableArray();
        this.bitwiseValue = ko.computed({
            read: function () {
                return vm.checkedList().reduce(function (prev, curr) {
                    return prev | curr;
                }, 0);
            },
            write: function (myVal) {
                vm.checkedList.removeAll();
                var placeValue = 1;
    
                while(myVal > 0) {
                    if((myVal % 2) == 1) {
                        alert(placeValue);
                        vm.checkedList.push(placeValue.toString());
                    }
    
                    myVal = myVal >>> 1;                    
                    placeValue = placeValue * 2;
                }
            }
        }, this);
    }
    
    ko.applyBindings(vm);
    

    Example fiddle here: http://jsfiddle.net/i_vargas3/RYQgg/

提交回复
热议问题