尽管您的方法可行,但这并不是更好的方法。
更好的方法是进行自定义绑定(http://knockoutjs.com/documentation/custom-bindings.html)。如果您不想手动进行绑定,那么有一个库(我不使用它,所以我不知道它们是否工作良好)具有 jqueryui 的绑定:http: //gvas.github.com /knockout-jqueryui/index.html
无论如何,您的示例的绑定将类似于:
ko.bindingHandlers.datepicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {},
$element = $(element),
$btn = $("<button class='btn' type='button'><i class='icon-calendar'></i></button>");
$element.datepicker(options);
$element.prop("readonly", true);
$element.wrap("<div class='input-append' />");
$element.after($btn);
$btn.click(function () {
$element.datepicker("show");
});
//handle the field changing
ko.utils.registerEventHandler(element, "change", function () {
var observable = valueAccessor(),
current = $(element).datepicker("getDate");
observable(current);
});
//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()),
current = $(element).datepicker("getDate");
if (value - current !== 0) {
$(element).datepicker("setDate", value);
}
}
};
在视图中:
<input type="text" id="yourid" data-bind="datepicker: yourobservable, datepickerOptions:{}" />