How can I get Knockout JS to data-bind on keypress instead of lost-focus?

后端 未结 4 514
终归单人心
终归单人心 2020-12-07 07:44

This example of knockout js works so when you edit a field and press TAB, the viewmodel data and hence the text below the fields is updated.

How can I chang

4条回答
  •  失恋的感觉
    2020-12-07 08:36

    Jeff Mercado's answer is fantastic, but unfortunately broken with Knockout 3.

    But I found the answer suggested by the ko devs while working through Knockout 3 changes. See the bottom comments at https://github.com/knockout/knockout/pull/932. Their code:

    //automatically add valueUpdate="afterkeydown" on every value binding
    (function () {
        var getInjectValueUpdate = function (allBindings) {
            return {
                has: function (bindingKey) {
                    return (bindingKey == 'valueUpdate') || allBindings.has(bindingKey);
                },
                get: function (bindingKey) {
                    var binding = allBindings.get(bindingKey);
                    if (bindingKey == 'valueUpdate') {
                        binding = binding ? [].concat(binding, 'afterkeydown') : 'afterkeydown';
                    }
                    return binding;
                }
            };
        };
    
        var valueInitHandler = ko.bindingHandlers.value.init;
        ko.bindingHandlers.value.init = function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            return valueInitHandler(element, valueAccessor, getInjectValueUpdate(allBindings), viewModel, bindingContext);
        };
    }());
    

    http://jsfiddle.net/mbest/GKJnt/

    Edit Ko 3.2.0 now has a more complete solution with the new "textInput" binding. See SalvidorDali's answer

提交回复
热议问题