Using the Editable grid example from knockout and binding Steve Sanderson Blog , I am trying to get a DatePicker or datetimepicker to work in an editable grid. I started by using the datepicker binding established by Ryan Niemeyer , but this does not work for the observable array.
So the code looks like this:
ko.bindingHandlers.datetimepicker = { init: function(element, valueAccessor, allBindingsAccessor) { //initialize datepicker with some optional options var options = allBindingsAccessor().datetimepickerOptions || {}; $(element).datetimepicker(options); //handle the field changing ko.utils.registerEventHandler(element, "change", function() { var observable = valueAccessor(); console.log("changing", observable); observable($(element).datetimepicker("getDate")); }); //handle disposal (if KO removes by the template binding) ko.utils.domNodeDisposal.addDisposeCallback(element, function() { $(element).datetimepicker("destroy"); }); }, update: function(element, valueAccessor) { var value = ko.utils.unwrapObservable(valueAccessor()), current = $(element).datetimepicker("getDate"); console.log("updating"); if (value - current !== 0) { console.log("setting", value); $(element).datetimepicker("setDate", value); console.log("just set", $(element).datetimepicker("getDate")); } } };
with binding:
<td><input class ="datetimeClass" style="width:130px" data-bind="datetimepicker: CPDateString, uniqueName: true" /></td>
Any help or examples are appreciated. I know that this is related to every element in the observable array that is not observable, but new to Javascript I cannot figure out how to fix it.
I get an error: "string is not a function" in the Change event. If I add some code to try to make the field visible, like this:
$(initialData).each(function(gift) { this.CPDateString = ko.observable(this.CPDateString); });
then the datetimepicker works and correctly updates the browser, but the data is not published, so it does not update the actual array of gifts that is sent back:
var initialDataLocations = @Html.Raw(JsonConvert.SerializeObject(ViewBag.Locations)); var initialData = @Html.Raw(JsonConvert.SerializeObject(Model)); var viewModel = { availableLocations: ko.observableArray(initialDataLocations), gifts: ko.observableArray(initialData), save: function() { ko.utils.postJson(location.href, { gifts: this.gifts }) } };
Thanks in advance.