Bidirectional binding of data attribute with Knockout

I have something like that:

Html:

<label id="CustomerName" data-bind="text: name, attr: {'data-value': name}"></label>

Script:

var viewModel = {
   name : ko.observable("Original Name");
}

ko.applyBindings(viewModel);

I want to be able to change the data attribute programmatically with the help of jQuery.

$("#CustomerName").data("value", "NewName");

After changing the value of the data attribute, I don't see my change back in the linked property of the viewmodel.

Is it a normal behavior of Knockout to not synching viewmodel properties bound to data attribute?

If the data attribute are not bidirectional, what would be the best way to do this? Hidden field?? You understand I don't want input field like textbox? Yeah! Ahhh ok,... :)

Thank you.

Answers


If you're changing the value in jQuery outside of your Knockout view model, you have to do the following:

$('#CustomerName').val('NewName'); // Works the same way as your example
$('#CustomerName').change();

Since Knockout subscribes to the change() event on its bindings, you have to fire the change() event so that Knockout knows it changed. You don't need the "data-" attribute, just bind the text to the observable on your view model, Knockout takes care of the rest.


You could also get the data for the element with:

 ko.dataFor($("#CustomerName")[0])("NewName")

And set it like that.

I'd suggest that you make a bindingHandler for this which keeps in sync the data attribute and the value. You can hook into the change event for the attribute and update the observable.


Need Your Help

Authentication in a mobile app

facebook forms-authentication mobile-application

We are developing a hybrid mobile app (code is written in HTML and runs on browser shell as a native app on the device). We need to authenticate the user against an external security manager. I've ...