Knockoutjs computed passing parameters

前端 未结 4 2047
终归单人心
终归单人心 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:23

    There is no reason to use a computed value. Simply define a function in your View Model and bind the checked to it.

    Below is a very simplistic example.

    --

    HTML

    
    
    

    JS

    var MyViewModel=function(){
        this.isEven = function(num) {
            return (num % 2) == 0;
        };
    };
    ko.applyBindings(new MyViewModel());
    

    ​--

    That being said it is a good idea to try and push as much of the logic into your View Model as is possible. It would be advisable to create a View Model that models your checkbox as an object, and then the logic as to if the checkbox should be checked could be encapsulated inside.

    --

    EDIT: Based on the requirement to do two-way binding I have written an extender to manage an observable.

    http://jsfiddle.net/jearles/j6zLW/5/

    ko.extenders.bitwise = function(target, bitCount) { 
        target.bits = [];    
        target.checked = ko.observableArray();
    
        // Create bit array based on requested number of bits
        for (i=bitCount-1; i>=0; i--) {
            target.bits.push(''+Math.pow(2, i));
        }        
    
        // Define a function to create bits
        function makeBits(newValue) {
           var num = !isNaN(newValue) ? parseInt(newValue) : 0;
           var arr = [];
           for (i=0; i -1) num += parseInt(target.bits[i]);
           }
           target(num);
        }
    
        // Create initial bits
        makeBits(target());
    
        // Make bits whenever the value changes
        target.subscribe(makeBits);
    
        // Make number whenever the bits change
        target.checked.subscribe(makeBitwise);
    
        // Return the original observable
        return target;
    };
    
    var MyViewModel=function(){
        var self = this;
        this.number = ko.observable(2).extend({ bitwise: 8});
    
    };
    ko.applyBindings(new MyViewModel());​
    

提交回复
热议问题