I'm using Twitter Bootstrap.DatePicker with knockout. The problem that I'm having is that I can't get it to work properly. It's working fine when there is an initial date, but when there is no initial date I am getting the following error: Uncaught TypeError: Cannot call method 'getTime' of undefined
HTML
<div id='target'>
<input data-bind='datepicker: test_date'/>
<div data-bind="text: test_date"></div>
<input data-bind='datepicker: test_date_empty'/>
</div>
BindingHandler
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());
if (!widget.date) {
return;
}
if (_.isString(widget.date)) {
widget.date = new Date(widget.date);
}
widget.setValue();
}
}
};
var model = {
test_date: ko.observable(),
test_date_empty: ko.observable()
};
ko.applyBindings(model, $("#target")[0]);
model.test_date("2012/04/04")
model.test_date_empty()
I have created a JSFiddle where the behaviour is demonstrated http://jsfiddle.net/DirkMolman/ACKyp/5/
I's using knockout 2.3.0 and Bootstrap.datepicker 1.1.3.1
I hope that someone can help me solve this problem.
I don't have much experience with the Bootstrap DatePicker before, but it looks like you could use the
setDate
API and if the value is empty, then force achange
event on the element with an empty value. Based on your current code, in yourupdate
it would look something like:http://jsfiddle.net/rniemeyer/JRCsb/