Using the Editable Grid Example from Knockout, and tying in the Steve Sanderson blog, I am trying to get a DatePicker or datetimepicker to work within the editable grid. I started by using the datepicker binding set up by Ryan Niemeyer, but this doesn't work for an observable array.
So the code looks like:
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 the binding:
<td><input class ="datetimeClass" style="width:130px" data-bind="datetimepicker: CPDateString, uniqueName: true" /></td>
Any help or examples would be greatly appreciated. I know this has to do with each item in the observeablearray is not itself observable, but new to Javascript I can't figure out how to fix it.
I get an error: "string is not a function" on the Change event. If I add some code to try and make the field observable, like so:
$(initialData).each(function(gift) {
this.CPDateString = ko.observable(this.CPDateString);
});
then the datetimepicker works, and updates the browser correctly, but the data isn't posted, so it isn't updating the actual gifts array that is getting posted back by:
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.