我使用以下代码创建了一个DataPicker控件。
<div id="date" data-win-control="WinJS.UI.DatePicker"></div>
我想使用knockout绑定到从WinJS生成的3个选择列表。有没有办法使用敲除声明性数据绑定绑定到生成的选择列表?
答案 0 :(得分:3)
ko.bindingHandlers['winjsDatePicker'] = {
init: function (element, valueAccessor, allBindingsAccessor) {
var value = valueAccessor(),
allBindings = allBindingsAccessor(),
options = allBindings['winjsDatePickerOptions'] || {};
options['current'] = value;
// Flatten the options for DatePicker
var dpOptions = {};
ko.utils.arrayForEach([
'calendar', 'current', 'datePattern', 'disabled', 'element',
'maxYear', 'minYear', 'monthPattern', 'yearPattern'
], function (prop) {
if (options.hasOwnProperty(prop)) {
dpOptions[prop] = ko.utils.unwrapObservable(options[prop]);
}
});
// Use jQuery to store the value-observable with the element
$(element).data('winjsDatePickerCurrent', value);
// Create the DatePicker, and pass it the options
var dp = new WinJS.UI.DatePicker(element, dpOptions);
// Wire up the onchange event
dp.addEventListener("change", function() {
var value = $(element).data('winjsDatePickerCurrent');
if (ko.isWriteableObservable(value)) {
value(dp.current);
}
});
},
update: function (element, valueAccessor, allBindingsAccessor) {
var dp = element.winControl,
value = valueAccessor(),
allBindings = allBindingsAccessor(),
options = allBindings['winjsDatePickerOptions'] || {};
options['current'] = value;
// Update the value-observable
$(element).data('winjsDatePickerCurrent', value);
// Update any properties
ko.utils.arrayForEach([
'calendar', 'current', 'datePattern', 'disabled', 'element',
'maxYear', 'minYear', 'monthPattern', 'yearPattern'
], function (prop) {
if (options[prop] !== undefined) {
dp[prop] = ko.utils.unwrapObservable(options[prop]);
}
});
}
};
<div data-bind="winjsDatePicker: date"></div>
<div data-bind="winjsDatePicker: date, winjsDatePickerOptions: { minYear: 2012 }"></div>
答案 1 :(得分:1)
我可能会研究一下自定义绑定。您仍然可以为DatePicker使用声明性标记,但在自定义绑定中实例化DatePicker可能更容易。
注意:我没有机会测试这个,但它可能会指向正确的方向。另外,我认为在WinJS世界中,他们更喜欢你做data-win-bind="winControl.current: yourprop"
,但如果你想使用KO,可能就有办法了。
ko.bindingHandlers.winDatePicker = {
init: function (element, valueAccessor) {
var currentDate = valueAccessor() || {};
// In order for this to be true, you would had to call WinJS.UI.processAll() and *then* ko.applyBindings()
if (element.winControl) {
element.winControl.current = currentDate;
}
},
update: function (element, valueAccessor) {
var currentDate = valueAccessor() || {};
if (element.winControl) {
element.winControl.current = currentDate;
}
}
};
/// <div data-bind="winDatePicker: myObservable" data-win-control="WinJS.UI.DatePicker" />
你可以看看我制作的这个要点。不过没有保修!在使用此代码之前,您需要致电WinJS.Binding.processAll
:https://gist.github.com/4183235