使用Knockout.js如何将Date属性绑定到HTML5日期选择器? [英] Using Knockout.js how do bind a Date property to a HTML5 date picker?
问题描述
(目前仅适用于Chrome,因为大多数浏览器尚未为输入类型=日期实现日期选择器)
在下面的示例中,MyDate以具有当前日期的Date对象开始,但日期输入(它希望其格式为格式为YYYY / MM / DD的字符串)不会选择此项。
In the following example MyDate starts out as a Date object with the current date, but this isn't picked up by the date input (which expects its format to be a string in format YYYY/MM/DD).
一旦你在选择器中选择了一个日期,MyDate就会变成上面格式的字符串。
Once you've picked a date in the picker then MyDate becomes a string in format above.
你怎么能绑定这样,MyDate保持javascript日期并被输入控件正确解释?
How can you bind this so MyDate stays a javascript Date and is interpreted by the input control correctly?
参见 http://jsfiddle.net/LLkC4/3/: -
See See http://jsfiddle.net/LLkC4/3/ :-
<input data-bind="value : MyDate" type="date">
<hr>
<span data-bind="html: log" />
<script>
var viewModel = {
MyDate : ko.observable(new Date()),
log : ko.observable(""),
logDate : function () {
this.log(this.log() + this.MyDate() + " : " +
typeof(this.MyDate()) + "<br>");
}
};
viewModel.MyDate.subscribe(function (date) {
viewModel.logDate();
});
ko.applyBindings(viewModel);
viewModel.logDate()
</script>
推荐答案
虽然@amakhrov的回答会起作用(甚至可以如果使用像@Stijn那样的可写可计算的observable,那就更好了。我决定使用自定义绑定来做到这一点。
While @amakhrov answer will work (and would be even better if used writeable computed observable like sujested by @Stijn) I decided to do this using Custom Bindings.
这样做的主要优点是可重用性 - 我只需要使用 data-bind =datePicker:MyDate
想要将其联系起来。我还可以修改输入元素的其他属性,这样如果绑定到复杂的jQuery(和其他)控件,这可能非常有用。
The main advantage of doing this is reusability - I just have to use data-bind="datePicker : MyDate"
whereever I want to tie this in. I can also modify other properties of the input element so this could be really useful if binding to complex jQuery (and other) controls.
(请阅读此处了解更多关于3个选项的赞成/反对意见做这种事情)
(Read here for more pro/cons about the 3 choices to do this sort of thing)
HTML
<input data-bind="datePicker : MyDate" type="date">
JS
ko.bindingHandlers.datePicker = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
// Register change callbacks to update the model
// if the control changes.
ko.utils.registerEventHandler(element, "change", function () {
var value = valueAccessor();
value(new Date(element.value));
});
},
// Update the control whenever the view model changes
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var value = valueAccessor();
element.value = value().toISOString();
}
};
var viewModel = {
MyDate : ko.observable(new Date())
};
ko.applyBindings(viewModel);
请参阅 http ://jsfiddle.net/LLkC4/5/
这篇关于使用Knockout.js如何将Date属性绑定到HTML5日期选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!