01 June 2012

KnockoutJS force viewModel update

The KnockoutJS (KO) has a binding parameter named valueUpdate that defines which browser event KO should use to detect changes.

The default is on change: As the documentation says: "change" (default)
- updates your view model when the user moves the focus to a different control, or in the case of select elements, immediately after any change

Now let us say that you are using the jquery datepicker on a textbox.
After the date is selected the texbox has the value, but KO doesn't update the value on it's model, because there isn't any change event on the control.

To force that KO updates the model for the date textbox, the change event must be fired:
$("#textboxID").trigger("change");

Another possible solution is to create a custom binding for the jQuery datepicker.
The skeleton to specifiy a custom binding is:
ko.bindingHandlers.myCustomBinding = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel) {

    },
    update: function(element, valueAccessor, allBindingsAccessor, viewModel) {

    }
};
You can create a datepicker binding:
ko.bindingHandlers.datepicker= {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
      var parameters = allBindingsAccessor().datepickerParameters || {};
      $(element).datepicker(parameters);

       //handle the field changing
    },
    update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
       //handle the field changing
    }
};

and use it as:

No comments: