Slight
Slight

Reputation: 1582

Knockout 'textInput' and 'Value' binding not catching changes made from JS

Using the latest knockout 3.3.0 and jquery 1.11.0, any changes made to an input element from JS will not update observables bound to that element via textInput or value.

Example mock code:

html

<input id="test" type="text" data-bind="textInput: testObs" />

js

$("#test").val("someVal");

Example fiddle: http://jsfiddle.net/whxj5Lf6/

Is there a workaround to this so that such changes will be caught?

Upvotes: 4

Views: 2103

Answers (2)

Michael Best
Michael Best

Reputation: 16688

Knockout listens for events to know that the value has changed. Specifically it will respond to the change event, which is easy to trigger with jQuery:

$("#test").val("test2").change();

http://jsfiddle.net/mbest/whxj5Lf6/2/

When interfacing with external components, it's often better to use a custom binding rather than the built-in value or textInput bindings. For example, here's a custom binding for use with the jQuery UI datapicker.

Upvotes: 4

PaulShovan
PaulShovan

Reputation: 2134

According to knockoutjs documentation, the value of an observable will update when the change event will occur.

Whenever the user edits the value in the associated form control, KO will update the property on your view model. KO will always attempt to update your view model when the value has been modified and a user transfers focus to another DOM node (i.e., on the change event), but you can also trigger updates based on other events by using the valueUpdate parameter

There is only one valueUpdate parameter exists that matches the criteria of your problem. The input parameter but it has some limitations according to documentation...

"input" - updates your view model when the value of an or element changes. Note that this event is only raised by reasonably modern browsers (e.g., IE 9+).

So, I think the best choice for you is to take the solution provided by Michael Best, trigger the change() event manually as following...

$("#test").val("test2").change();

Upvotes: 0

Related Questions