我有一个datetimepicker的视图。我无法在Knockout中绑定它。由于日期时间选择器结束时有一个文本框,我以与其他文本框相同的方式绑定它(工作正常)并假设它包含文本格式的日期时间值,但它没有绑定。
<div class='input-group date' id='datetimepicker1'>
<input type="text" class="form-control" id="estimatedTime" data-bind="value: estimatedTime">
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
<input type="number" class="form-control" id="estimatedAmt" data-bind="value: estimatedAmount">
这是我的脚本,它不适用于datetimepicker(estimatedTime),但适用于普通文本框(EstimatedAmount)。
var Model = function () {
var self = this;
self.estimatedTime= ko.observable(initialData.estimatedTime);
self.estimatedAmount= ko.observable(initialData.EstimatedAmount);
self.update = function () {
});
}
ko.applyBindings(new Model());
为什么有不同之处,最简单的解决方法是什么?
答案 0 :(得分:0)
您需要binding handler将另一个DOM操作实体合并到Knockout中。有关示例,请参阅此datetimepicker fiddle。
ko.bindingHandlers.datepicker = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
//initialize datepicker with some optional options
var options = {
format: 'DD/MM/YYYY HH:mm',
defaultDate: valueAccessor()()
};
if (allBindingsAccessor() !== undefined) {
if (allBindingsAccessor().datepickerOptions !== undefined) {
options.format = allBindingsAccessor().datepickerOptions.format !== undefined ? allBindingsAccessor().datepickerOptions.format : options.format;
}
}
$(element).datetimepicker(options);
var picker = $(element).data('datetimepicker');
//when a user changes the date, update the view model
ko.utils.registerEventHandler(element, "dp.change", function (event) {
var value = valueAccessor();
if (ko.isObservable(value)) {
value(event.date);
}
});
var defaultVal = $(element).val();
var value = valueAccessor();
value(moment(defaultVal, options.format));
},
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());
if (widget.date) {
widget.setValue();
}
}
}
};