Reputation: 995
I'm new to Knockout. I have a Viewmodel like this:
var Booking = function(data) {
var self = this;
self.BookingID = ko.observable(data.BookingID);
self.BookingCustomerOrderID = ko.observable(data.BookingCustomerOrderID);
self.BookingName = ko.observable(data.BookingName);
self.BookingTreatmentGroupID = ko.observable(data.BookingTreatmentGroupID);
self.BookingStartTime = ko.observable(data.BookingStratTime);
self.BookingEndTime = ko.observable(data.BookingEndTime);
In my form I'd like to let the user change time of the StartTime and EndTime. Can I make a custom binding to just the time part leaving the datepart from the input field and make this update the model?
To just display the value this works fine, but this does not update the viewmodel.
ko.bindingHandlers.timeVal = {
update: function (element, valueAccessor) {
var value = valueAccessor();
var date = moment(value());
var strDate = date.format('HH:mm');
$(element).val(strDate);
}
};
Upvotes: 0
Views: 482
Reputation: 5147
Looking at the documentation, you can register an event handler onto the element in your init method, and use that to update your observable. Something like this:
ko.bindingHandlers.hasFocus = {
init: function(element, valueAccessor) {
$(element).change(function() {
if(this.val() != valueAccessor())
{
this.val(valueAccessor());
}
});
},
update: function(element, valueAccessor) {
var value = valueAccessor();
var date = moment(value());
var strDate = date.format('HH:mm');
$(element).val(strDate);
}
};
Upvotes: 1