//定义绑定,http://knockoutjs.com/documentation/custom-bindings.html ko.bindingHandlers.[CustomLogic]={ init:function(element,valueAccessor,allBindings,viewModel,bindingContext){} update:functing(element,valueAccessor,allBindings,viewModel,bindingContext){} }
//element: 调用绑定的dom元素;
//valueAccessor : 值访问者,可以获取到当前绑定的值;
//allBindings : 元素所有的绑定,可以获取到当前对象所有注册的绑定;
//viewModel : Model对象,可以获取到当前对象model的所有值;
//bindingContext : 上下文对象,$data、$index、$parent、$parentContext、$parents、$rawData、$root、$ko
<!--使用绑定--> <div data-bind="yourBindingName: someValue"> </div>
var ko = require("knockout");
var komap = require("/scripts/plugins/knockout/knockout.mapping.js");
_viewListModel = komap.fromJS(data);
ko.bindingHandlers.datePicker = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
//注册监听值改变事件
ko.utils.registerEventHandler(element, "change", function () {
var value = valueAccessor();
//转换
var string = "/Date(" + moment(element.value, "YYYY-MM-DD HH:mm").valueOf() + "+0800)/";
//转换后的值给原model
value(string);
});
},
// Update the control whenever the view model changes
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var value = valueAccessor();
element.value = moment(value()).format("YYYY-MM-DD HH:mm");
}
};
//绑定视图数据
ko.applyBindings({ lists: _viewListModel }, document.getElementById("listBody"));
<input type="text" data-bind="datePicker: EndDateTime" />