bootstrap datepicker

http://stackoverflow.com/questions/11121960/bootstrap-datepicker-with-knockout-js-databind

by kougiland

HTML

<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="http://knockoutjs.com/downloads/knockout-2.2.1.js"></script>
<script src="https://rawgithub.com/Aymkdn/Datepicker-for-Bootstrap/master/bootstrap-datepicker.js"></script>
<link rel="stylesheet" href="https://rawgithub.com/Aymkdn/Datepicker-for-Bootstrap/master/datepicker.css">
<div id='target'>
    <input data-bind='datepicker: test_date'/>
    
    <div data-bind="text: test_date"></div>
    
    <input data-bind='datepicker: test_date'/>
</div>

CSS

#target {
  margin: 2em;
}

JavaScript

ko.bindingHandlers.datepicker = {
    init: function(element, valueAccessor, allBindingsAccessor) {
      //initialize datepicker with some optional options
      var options = allBindingsAccessor().datepickerOptions || {};
      $(element).datepicker(options);
      
      //when a user changes the date, update the view model
      ko.utils.registerEventHandler(element, "changeDate", function(event) {
             var value = valueAccessor();
             if (ko.isObservable(value)) {
                 value(event.date);
             }                
      });
    },
    update: function(element, valueAccessor)   {
        var widget = $(element).data("datepicker");
         //when the view model is updated, update the widget
        if (widget) {
            widget.date = ko.utils.unwrapObservable(valueAccessor());
            widget.setValue();            
        }
    }
};

var model = {
    test_date: ko.observable(new Date('2012/12/12'))
};

ko.applyBindings(model, $("#target")[0]);