如何使用 Knockout.js 绑定 HTML5 日期选择器和其他输入类型?

How to bind HTML5 datepicker and other input types using Knockout.js?

我开始学习 knockout.js 并在使用 html5 表单域时遇到了一些问题。当我处理具有文本类型的 html5 输入字段元素时,一切顺利,但不幸的是我无法从 html5 datepicker 中获取和显示类型为日期的值。

我在 KnockoutJS 中找到了一些描述与日期选择器进行数据绑定的示例,但它们使用了一些其他来源(例如 moment.js 或 jQuery UI)以实现所需的结果。

因此,关于将 html5 日期选择器输入与 KnockoutJS 绑定而不包括任何额外的插件和库,并且不使用计算变量,您能否给我一些想法?

除此之外,我什至没有在 KO 的官方文档中找到任何解释如何使用 HTML5 的新输入类型(例如颜色、电子邮件、url、数字、范围和其他一些。因此,如果您能给我任何提示,我将不胜感激。

<h2>Set date</h2>
<!--input type "text" works well and the result is visible below whereas other input types are problematic-->
<input type="text" data-bind="value: addStart" /><br> 

From <input  type="date" data-bind="date: addStartDate" /> 
To <input type="date" data-bind="date: addEndDate" />

<input  type="color" data-bind="date: addColor" /> 
<input type="email" data-bind="date: addEmail" />
<input type="url" data-bind="date: addUrl" />
<input type="number" data-bind="date: addNumber" />
<input type="range" data-bind="date: addRange" />

<h2>Display date</h2>   
<strong data-bind="text: addStart" ></strong><br> 
<strong data-bind="text: timeLine" ></strong><br> 

<strong  type="color" data-bind="date: addColor"></strong> <br> 
<strong type="email" data-bind="date: addEmail"></strong><br> 
<strong type="url" data-bind="date: addUrl"></strong><br> 
<strong type="number" data-bind="date: addNumber"></strong><br> 
<strong type="range" data-bind="date: addRange"></strong><br>
var ViewModel = function() {
    var self = this;
    self.addStart = ko.observable();       
    self.addStartDate = ko.observable();  // date
    self.addEndDate = ko.observable();    // date

    self.addColor = ko.observable();    // Color
    self.addEmail = ko.observable();    // Email
    self.addUrl = ko.observable();      // Url
    self.addNumber = ko.observable();   // Number
    self.addRange = ko.observable();    // Number

};
// Activates knockout.js
ko.applyBindings(new ViewModel());

像对待 type='text' 一样对待那些新的 input 类型,并且只使用 value 绑定。参见:

ko.applyBindings({ val1: ko.observable(), val2: ko.observable(), val3: ko.observable() });
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

Date: <input type="date" data-bind="value: val1" />
<hr />
Color: <input type="color" data-bind="value: val2" />
<hr />
Email: <input type="email" data-bind="textInput: val3" />
<hr />
Etc.
<hr />
Confirm that view model actually changes / debug info:
<pre data-bind="text: ko.toJSON($root)"></pre>