knockoutjs databind with jquery controls
http://stackoverflow.com/questions/6399078/knockoutjs-databind-with-jquery-controls
by rpallas
HTML
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/themes/base/jquery-ui.css">
<script src="https://github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.debug.js"></script>
<script src="https://raw.github.com/timrwood/moment/1.7.2/min/moment.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<input type="text" data-bind="datepicker: myDate" />
<input type="text" data-bind="hourpicker: myDate" />
<input type="text" data-bind="minutepicker: myDate" />
<hr />
<button data-bind="click: setToCurrentDate">Set To Current Date</button>
<hr />
<div data-bind="text: displayDate"></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 options (or just use the defaults)
var options = allBindingsAccessor().datepickerOptions || {
dateFormat: 'dd/mm/yy',
showButtonPanel: true
};
$(element).datepicker(options);
//handle the field changing
ko.utils.registerEventHandler(element, "change", function () {
var observable = valueAccessor(),
newValue = $(element).datepicker("getDate"),
unixTimestamp = moment(newValue).unix();
observable(unixTimestamp);
});
//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()),
newValue = moment.unix(value).toDate(),
temp = new Date(2001, 8, 11, 8, 25),
current = $(element).datepicker("getDate");
if (newValue - current !== 0) {
$(element).datepicker("setDate", temp);
}
}
};
ko.bindingHandlers.hourpicker = {
init: function(element, valueAccessor, allBindingsAccessor) {
//handle the field changing
ko.utils.registerEventHandler(element, "change", function () {
var currentTimestamp = ko.utils.unwrapObservable(valueAccessor()),
observable = valueAccessor(),
newHourValue = $(element).val(),
// Construct a new date with only the hours changed
newDate = moment.unix(currentTimestamp).hours(newHourValue);
var newTimestamp = newDate.unix();
observable(newTimestamp);
});
},
update: function (element, valueAccessor) {
// Convert the value...