Chun ping Wang
Chun ping Wang

Reputation: 3929

knockout: valueUpdate on change from javascript code

Hi i know valueUpdate: afterkeydown will do model update after user input but I want to know how can i do valueUpdate automatically after some other javascript code changes value

I have a js code that does document.getElementById("input").value = "new value";

do i have to update model manually or what valueUpdate should i use.

Upvotes: 2

Views: 2863

Answers (2)

RP Niemeyer
RP Niemeyer

Reputation: 114792

If you trigger the change event for the element, then the element's binding (value) will pick up the change and process it normally.

However, generally you would want to make your updates through the view model and let the bindings handle setting the element's properties, but if you have 3rd party or existing code that interacts directly with the element that cannot be changed, then triggering the change event is a solution.

Knockout does include a utility to trigger an event properly cross-browser called ko.utils.triggerEvent.

Your code might look like:

   var elem = document.getElementById("input");
   elem.value = "new value";
   ko.utils.triggerEvent(elem, "change");

Upvotes: 6

Ben
Ben

Reputation: 338

After the line that updates the input value, call observable.valueHasMutated() on whichever observable corresponds to the input you're changing.

Upvotes: 1

Related Questions