knockoutjs databind with jquery controls

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

by madcapnmckay

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">
<script src="https://raw.github.com/datejs/Datejs/master/build/date.js"></script>
<input data-bind="datepicker: myDate, datepickerOptions: { minDate: new Date() }" />

<hr />

<button data-bind="click: setToCurrentDate">Set To Current Date</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) {
        $(element).datepicker({
            //dateFormat: "dd-mm-yy",
            dateFormat: "MM-yy",
            changeYear: true,
            changeMonth: true
        });

        //handle the field changing
        ko.utils.registerEventHandler(element, "change", function () {
            console.log("change registered");
                       
            var observable = valueAccessor();
            observable(Date.parse("01-" + $(element).val()));
        });

        //handle disposal (if KO removes by the template binding)
        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).datepicker("destroy");
        });

    },
    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(new Date("09/01/2011")),
    setToCurrentDate: function() {
        this.myDate(new Date());
    }
};

ko.applyBindings(viewModel);