Reputation: 887
I have a bootstrap datepicker widget, working great with Knockout: i.e., I can select a date, and the model is correctly updated. However, I cannot seem to be able to initially populate the date, when I first initialize my model.
Here is my HTML:
<div class="controls">
<input type="text" class="datepicker" data-date-format="dd-mm-yyyy" data-bind="datepicker: someDate" />
<div data-bind="text: someDate"></div>
And the corresponding JavaScript:
var self = this;
$('.datepicker').datepicker();
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());
widget.setValue();
}
}
}; // end KO binding datepicker
function AppViewModel() {
self.someDate = ko.observable(new Date('01/01/2004'));
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
And the corresponding JSFiddle: http://jsfiddle.net/philcms1/0mftjtk4/2/
How do I get the widget populated when the model is first bound?
Upvotes: 0
Views: 6540
Reputation: 7110
You can check a working sample here here (taken from Codinglookseasy)
As you said using value: myDate
fixed your issue.
Upvotes: 1
Reputation: 108
value:someDate
is definitely a more explicit way to go but you could also just call jquery datepicker's setDate method in the init callback as shown in
http://jsfiddle.net/zkgp0b4b/1/
Upvotes: 0