我正在尝试将 knockoutjs 与 tempusdominus datetimepicker 一起使用,并且自定义绑定有问题。绑定将在初始化期间工作,但通过 datepicker ui 进行的更改或不导致自定义绑定处理更新事件。请忽略缺少的图标,我认为这不是导致问题的原因。
ko.bindingHandlers.datepicker = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
//initialize datepicker with some optional options
var options = allBindings().datepickerOptions || {
format: 'MM/DD/YYYY HH:mm',
defaultDate: valueAccessor()()
};
$(element).datetimepicker(options);
//when a user changes the date, update the view model
ko.utils.registerEventHandler(element, "change.datetimepicker", function(event) {
var value = valueAccessor();
if (ko.isObservable(value)) {
value(event.date);
}
console.log("change.datetimepicker"); //, event.date.format());
});
},
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var val = ko.utils.unwrapObservable(valueAccessor());
if ($(element).datetimepicker) {
$(element).datetimepicker("date", val);
}
console.log("update called"); //, $(element).datetimepicker("date").format());
}
};
var viewModel = {};
function QuoteViewModel(data) {
var self = this;
self.dt2 = ko.observable(moment());
};
viewModel = new QuoteViewModel();
ko.applyBindings(viewModel);
/*
$("#datetimepicker1").on("change.datetimepicker", function (e) {
console.log("on change", e.date.format());
});
*/
<link href="https://cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/d004434a5ff76e7b97c8b07c01f34ca69e635d97/build/css/bootstrap-datetimepicker.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.js"></script>
<script src="https://cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/d004434a5ff76e7b97c8b07c01f34ca69e635d97/src/js/bootstrap-datetimepicker.js"></script>
<div class="col-sm-6">
<div class="form-group">
<div class="input-group date" id="datetimepicker1" data-target-input="nearest">
<input type="text" class="form-control datetimepicker-input" data-target="#datetimepicker1" data-bind="datepicker: dt2" />
<div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
</div>
</div>
</div>
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre> SCRIPT
https://jsfiddle.net/mh_surge/7yrze0Lv/6/
如果我取消注释底部添加非 ko 更改事件处理程序的代码,它总是按预期触发。这让我相信 ko.utils.registerEventHandler 可能存在问题,但该函数的源代码似乎很好。
为什么更新和更改事件在初始化期间仅被触发一次,我该如何解决?