Knockoutjs computed passing parameters

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

    Create a function whose sole purpose is to return a computed observable. It may take in parameters as you wanted. It will have to be a separate computed observable if you want it to be a two-way binding.

    Then in your binding, call that function with the appropriate arguments. The computed observable it returns will be bound to in your view and will update as usual.

    Here's a fiddle where I used this technique for creating event handlers. You can do something similar here.

    You can keep it clean by making the function a method on the observable. Either by adding to the ko.observable.fn prototype or adding it directly to the observable instance.

    ko.observable.fn.bit = function (bit) {
        return ko.computed({
            read: function () {
                return !!(this() & bit);
            },
            write: function (checked) {
                if (checked)
                    this(this() | bit);
                else
                    this(this() & ~bit);
            }
        }, this);
    };
    // or
    function ViewModel() {
        this.flags = ko.observable(0);
    
        this.flags.bit = function (bit) {
            return ko.computed({
                read: function () {
                    return !!(this() & bit);
                },
                write: function (checked) {
                    if (checked)
                        this(this() | bit);
                    else
                        this(this() & ~bit);
                }
            }, this);
        }.bind(this.flags);
    }    
    

    Then apply to your view

    
    
    
    
    

    Demo


    However if you are just trying to bind all those checkboxes to a single value in your view model, you don't need to do that. Use the checked binding on an array in your view model and give your checkboxes a value. Every checked value will be added to the array. And it will be a two way binding.

    
    
    
    
    
    var viewModel = {
        checkedValues: ko.observableArray([])
    };
    

    Demo

提交回复
热议问题