Dynamically bound elements with applyBindingsToNod

2019-02-12 16:05发布

问题:

In this example I have a dynamically bound input and div to the same property. But on altering text in input, changes are not reflected in the div element.

http://jsfiddle.net/rpuri/Bcps5/

ko.applyBindingsToNode(document.getElementById('input-health'), {
    value: vm.status(),
    valueUpdate: 'afterkeydown'
});

Declarative binding is not an option for me because I need to bind to shared elements in partial views (ASP.NET MVC).

Thanks

回答1:

You are binding to the value of the observable instead of the observable itself.

Try:

ko.applyBindingsToNode(document.getElementById('health'), {
    text: vm.status, // <- not invoking status, binding to the observable itself.
    valueUpdate: 'keydown'
});

ko.applyBindingsToNode(document.getElementById('input-health'), {
    value: vm.status,  
    valueUpdate: 'keydown'
});

http://jsfiddle.net/hwQsm/



回答2:

I used the preprocess feature (Knockout 3).

<input type="text" data-bind="value: LastName, vuClass: 'text'" />

ko.bindingHandlers.vuClass = {
    preprocess: function (value, name, addBindingCallback) {
        if (value == "'text'") {
            addBindingCallback('valueUpdate', "['afterkeydown', 'blur']");
        }

        // ...
        // Check other values.
        // ...

        return value;
    }
};


标签: knockout.js