knockoutjs databind with jquery controls

http://stackoverflow.com/questions/6399078/knockoutjs-databind-with-jquery-controls

by macropus

HTML

<script src="https://github.com/jquery/jquery-tmpl/raw/master/jquery.tmpl.js"></script>
<script src="https://github.com/SteveSanderson/knockout/raw/master/build/output/knockout-latest.debug.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/themes/base/jquery-ui.css">
<input data-bind="datepicker: myDate, datepickerOptions: {  }" />

<hr />

<button data-bind="click: setToCurrentDate">Set To Current Date</button>
<button data-bind="click: getValue">Show Value</button>

<hr />

<div data-bind="text: myDate"></div>

CSS

td, th { padding: 5px; border: solid 1px black; }
th { color: #666; }
a { font-size: .75em; }

JavaScript

ko.bindingHandlers.datepicker = {
    init: function(element, valueAccessor, allBindingsAccessor) {
        //initialize datepicker with some optional options
        var options = allBindingsAccessor().datepickerOptions || {};
        $(element).datepicker(options);
        
        //handle the field changing
        ko.utils.registerEventHandler(element, "change", function() {
            var observable = valueAccessor();
            observable($(element).datepicker("getDate"));
        });

        //handle disposal (if KO removes by the template binding)
        ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
            $(element).datepicker("destroy");
        });
        
        //handle .Net DateTime
        var value = ko.utils.unwrapObservable(valueAccessor());
        var obs = valueAccessor();
        
        if (!isNaN(obs().replace(/\/Date\((-?\d+)\)\//, '$1'))) {
            obs(new Date(parseInt(value.replace(/\/Date\((-?\d+)\)\//, '$1'))));
            $(element).datepicker("setDate", obs());
        }
    },
    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor()),
            current = $(element).datepicker("getDate");
        
        if (value - current !== 0) {
            $(element).datepicker("setDate", value);   
        }
    }
};

var viewModel = {
    myDate: ko.observable("/Date(1000001352100)/"),
    setToCurrentDate: function() {
        this.myDate(new Date());
    },
    getValue: function() {
        alert(this.myDate().getTime());
    }
};

ko.applyBindings(viewModel);