4

I work on a website with the durandal template.

I have this bindingHandlers for my dates:

ko.bindingHandlers.date = {
    update: function (element, valueAccessor, allBindingsAccessor) {
        var value = valueAccessor();  // 'Mon Sep 10 2012 02:00:00 GMT+0200 (Paris, Madrid (heure d’été))'; 
        var date = moment(value());
        $(element).val((date.format('DD/MM/YYYY')));
    }
};

Here is the call in my view:

<input type="text" class="datepicker" data-bind="date: demandDate" /> 

This is used for formatting my dates in the correct format. It works I mean my date is correctly formatted in my input field.

But the problem is that whenever the date is modified in the input field, the system did not detect any change.

If I replace the 'date' by 'value' it is correctly interpreted when the value changed but I miss formatting:

<input type="text" class="datepicker" data-bind="value: demandDate" /> 

Any idea?

AndreyAkinshin
  • 18,603
  • 29
  • 96
  • 155
Bronzato
  • 9,438
  • 29
  • 120
  • 212

1 Answers1

8

The update: of the binding handler is fired after valueHasMutated() is issued from the knockout.js ViewModel. If you want to correctly apply changes to the ViewModel from your custom bindingHandler then you need to create an event handler in init: for the change event of the input and then issue a change to the ViewModel.

Example:

ko.bindingHandlers.date = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        ko.utils.registerEventHandler(element, 'change', function (event) {
            valueAccessor().demandDate($(element).val());
        }
    },
    update: function (element, valueAccessor, allBindingsAccessor) {
        var value = valueAccessor();  // 'Mon Sep 10 2012 02:00:00 GMT+0200 (Paris, Madrid (heure d’été))'; 
        var date = moment(value());
        $(element).val((date.format('DD/MM/YYYY')));
    }
};
Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100
  • Thank you for suggesting me an orientation. A complete solution can be found here: http://stackoverflow.com/questions/6612705/knockout-with-jquery-ui-datepicker – Bronzato Mar 29 '13 at 12:34
  • Wouldn't valueAccessor()($(element).val()); make more sense than valueAccessor().demandDate($(element).val()); to make this binding more reusable? – MrB Jul 23 '14 at 21:17