I am trying to create a page using knockout, the model contains an observable array. One of the properties in each array item is a date, and I am trying to use a jquery ui datepicker.
I found an example of a custom bindingHandler for a datepicker in this question. However, when I tried to use it in my code, I get a javascript error during the change event handler.
My simplified code:
<table>
<thead>
<tr>
<th>My Date</th>
</tr>
</thead>
<tbody data-bind='foreach: visits'>
<tr>
<td><input data-bind='datepicker: MyDate' /></td>
</tr>
</tbody>
</table>
<script type="text/javascript">
ko.bindingHandlers.datepicker = {
init: function(element, valueAccessor, allBindingsAccessor) {
$(element).datepicker({ dateFormat: 'dd/mm/yy' });
//handle the field changing
ko.utils.registerEventHandler(element, "change", function() {
//get the value accessor
var observable = valueAccessor();
//assign the observable value - code breaks here with 'Function expected'
observable($(element).datepicker("getDate"));
});
//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());
//handle date data coming via json from Microsoft
if (String(value).indexOf('/Date(') == 0) {
value = new Date(parseInt(value.replace(/\/Date\((.*?)\)\//gi, "$1")));
}
var current = $(element).datepicker("getDate");
if (value - current !== 0) {
$(element).datepicker("setDate", value);
}
}
};
var VisitModel = function(visits) {
var self = this;
self.visits = ko.observableArray(visits);
self.getVisitsJSON = function() {
return ko.utils.stringifyJson(self.visits);
}
};
var visitModel = new VisitModel([{"MyDate":"01/01/2013"}]);
ko.applyBindings(visitModel);
</script>
As in the comments in my code, I get an error saying 'Function expected' when I call observable($(element).datepicker("getDate"));
. I am quite new to knockoutjs and I am not sure why I am getting this error, can anyone help explain?