knockoutjs databind with jquery controls
http://stackoverflow.com/questions/6399078/knockoutjs-databind-with-jquery-controls
by Princa
HTML
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/themes/base/jquery-ui.css">
<script src="http://knockoutjs.com/downloads/knockout-2.2.1.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/datejs/1.0/date.min.js"></script>
<input data-bind="datepicker: myDate, datepickerOptions: { minDate: new Date() }, text: myDate" />
<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) {
//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();
var date= Date.parse($(element).val());
observable(date.toString("MM/dd/yyyy"));
//observable($(element).datepicker("getDate"));
});
//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");
var d = Date.parse(value);
if (value - current !== 0) {
$(element).datepicker("setDate", d.toString("MM/dd/yyyy"));
}
}
};
var viewModel = {
myDate: ko.observable(new Date("09/01/2011").toString("MM/dd/yyyy")),
setToCurrentDate: function() {
this.myDate(new Date().toString("MM/dd/yyyy"));
}
};
ko.applyBindings(viewModel);