Asle G Asle G - 5 months ago 82
Javascript Question

How to make bootstrap-datetimepicker work with knockout on Firefox

I have a date time variable "whenDateTime" that is read from my db on the format (YYYY-MM-DDTHH:mm:ss.000).
I want to set a datetimepicker with this date time, then be able to manipulate it, and of course write it back to my db.

For some reason the datetimepicker will not trigger. Where do I go wrong?

This is my view model:

function ViewModel() {
var self = this;

self.whenDateTime = ko.observable("2016-04-09T19:24:48.000");

self.viewWhenDateTime = ko.computed({
read: function () {
var mydate = self.whenDateTime();
if (!mydate) {
return null;
} else {
return moment(mydate).format("DD.MM.YYYY HH:mm");
}
},
write: function (newVal) {
var reversed = moment(newVal).format();
self.whenDateTime(reversed);
}
});
}


The bindingHandlers is like this:

ko.bindingHandlers.dateTimePicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().dateTimePickerOptions || {};
$(element).datetimepicker(options);

//when a user changes the date, update the view model
ko.utils.registerEventHandler(element, "dp.change", function (event) {
var value = valueAccessor();
if (ko.isObservable(value)) {
if (event.date != null && !(event.date instanceof Date)) {
value(event.date.toDate());
} else {
value(event.date);
}
}
});

ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
var picker = $(element).data("DateTimePicker");
if (picker) {
picker.destroy();
}
});
},
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var picker = $(element).data("DateTimePicker");
//when the view model is updated, update the widget
if (picker) {
var koDate = ko.utils.unwrapObservable(valueAccessor());

//in case return from server datetime i am get in this form for example /Date(93989393)/ then fomat this
koDate = (typeof (koDate) !== 'object') ? new Date(parseFloat(koDate.replace(/[^0-9]/g, ''))) : koDate;

picker.date(koDate);
}
}
};


Fiddle: http://jsfiddle.net/AsleG/v54hnxur/

Answer

When I run the fiddle (https://jsfiddle.net/9aLvd3uw/237/), it actually shows 09/04/2016 7:24 PM for 2016-04-09T19:24:48.000 and when I change the input date it gets changed properly. I couldn't replicate what you mentioned.

Note whenever moment.js wants to parse a date if that date is undefined or provided in a wrong format, it displays the current date instead.