我正在尝试将一个日期选择器绑定到我的模板属性中,如下例所示:http://jsfiddle.net/H8xWY/130/
从小提琴手看起来非常简单,但问题是当我专注于日期文本框时,日期选择器根本不会出现。也没有控制台错误。不确定为什么没有发生什么,我错过了什么?
我的模特:
var MyViewModel = function(model) {
var self = this;
self.date = ko.observable(new Date());
}
我的模板:
<div id="my-form">
<input data-bind="datepicker: date, datepickerOptions: { minDate: new Date() }" />
</div>
<script src="models/my-model.js" type="text/javascript"></script>
<script type="text/javascript">
var target = document.getElementById("my-form");
var data = @Html.Raw(Json.Encode(Model));
var myViewModel = new MyViewModel(data);
ko.applyBindings(myViewModel, target);
</script>
答案 0 :(得分:0)
添加日期选择器的分类扩展
ko.bindingHandlers.datepicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {};
$(element).datepicker(options);
//handle the field changing
ko.utils.registerEventHandler(element, "change", function () {
var observable = valueAccessor();
observable($(element).datepicker("getDate"));
});
//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());
//handle date data coming via json from Microsoft
if (String(value).indexOf('/Date(') == 0) {
value = new Date(parseInt(value.replace(/\/Date\((.*?)\)\//gi, "$1")));
}
current = $(element).datepicker("getDate");
if (value - current !== 0) {
$(element).datepicker("setDate", value);
}
}
};