Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BindingHandlers on my input with knockout not correctly interpreted

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?

like image 661
Bronzato Avatar asked Sep 08 '25 06:09

Bronzato


1 Answers

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')));
    }
};
like image 157
Konstantin Dinev Avatar answered Sep 09 '25 21:09

Konstantin Dinev