Change event on select with knockout binding, how can I know if it is a real change?

前端 未结 11 1890
独厮守ぢ
独厮守ぢ 2021-01-30 08:05

I am building a permissions UI, I have a list of permissions with a select list next to each permission. The permissions are represented by an observable array of objects which

11条回答
  •  盖世英雄少女心
    2021-01-30 08:43

    I use this custom binding (based on this fiddle by RP Niemeyer, see his answer to this question), which makes sure the numeric value is properly converted from string to number (as suggested by the solution of Michael Best):

    Javascript:

    ko.bindingHandlers.valueAsNumber = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var observable = valueAccessor(),
                interceptor = ko.computed({
                    read: function () {
                        var val = ko.utils.unwrapObservable(observable);
                        return (observable() ? observable().toString() : observable());
                    },
                    write: function (newValue) {
                        observable(newValue ? parseInt(newValue, 10) : newValue);
                    },
                    owner: this
                });
            ko.applyBindingsToNode(element, { value: interceptor });
        }
    };
    

    Example HTML:

    
    

提交回复
热议问题