Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuerybUI datepicker() with dynamic knockout loop

I have got this templated knockout-loop:

<div id="accordion" data-bind="jqAccordion:{},template: {name: 'task-template',foreach: Tasks,afteradd: function(elem){$(elem).trigger('valueChanged');}}">.   </div> 

<script type="text/html" id="task-template">
     <div data-bind="attr: {'id': 'Task' + TaskId}" class="group">
          <h3><b><input name="TaskName" data-bind="value: TaskName  /></b></h3>
          <p>
             Due Date: <input class="datepicker" data-bind="myDatepicker : {}, value: taskDueDate" />
          </p>
     </div>
</script>

Where datepicker is a jQuery Ui datepicker function:

ko.bindinghandler.myDatepicker =  $(function() {
    init: function( element, valueAccessor) {

        $(element).datepicker({
           changeMonth: true,
           changeYear: true
        });
    }), 
    etc.
}

why does this not work?

Symptoms are: the calender is showing and the widget respond to my interactions but no date is returned to the input-field. Any clues?

Thank you in advance!

like image 955
Asle G Avatar asked Nov 11 '22 21:11

Asle G


1 Answers

You need to bind some viewModel attribute to the datepicker binding... You're overthinking that part.

But you do need to do some special handling for when the datepicker changes the element's value because it will otherwise mess up the way knockout normally intercepts the change.

Set up the binding like this...

HTML:

<div id="accordion" data-bind="jqAccordion:{},template: {name: 'task-template',foreach: Tasks,afteradd: function(elem){$(elem).trigger('valueChanged');}}">.   </div> 

<script type="text/html" id="task-template">
     <div data-bind="attr: {'id': 'Task' + TaskId}" class="group">
          <h3><b><input name="TaskName" data-bind="value: TaskName  /></b></h3>
          <p>
             Due Date: <input class="datepicker" data-bind="myDatepicker : taskDueDate" />
          </p>
     </div>
</script>

And the handler like so:

ko.bindingHandlers.myDatepicker =  {
    init: function(element, valueAccessor) {
        var unwrappedObs = valueAccessor();
        $(element).val(ko.unwrap(unwrappedObs));
        $(element).datepicker({
           changeMonth: true,
           changeYear: true
        });
        ko.utils.registerEventHandler(element, "change", function () {
            var unwrappedObs = valueAccessor(),
            val = $(element).datepicker("getDate");
            unwrappedObs(val);
        });
    } 
};

Here's a fiddle: http://jsfiddle.net/brettwgreen/nmb6c6gq/

like image 103
Brett Green Avatar answered Nov 15 '22 00:11

Brett Green