您正在寻找custom-binding的主要用途。在这里查看一个很好的指南
ko.bindingHandlers.dateConverter = {
init: function (element, valueAccessor, allBindingsAccessor) {
var underlyingObservable = valueAccessor();
var options = allBindingsAccessor().dateConverterOptions
|| { /* set defaults here */ };
var interceptor = ko.computed({
read: function() {
return underlyingObservable();
},
write: function(newValue) {
var current = underlyingObservable(),
convertedDate;
/* do some kind of conversion here, using the 'options' object passed */
if (convertedDate !== current) {
underlyingObservable(convertedDate);
}
else if (newValue !== current.toString()) {
underlyingObservable.valueHasMutated();
}
}
});
ko.applyBindingsToNode(element, { value: interceptor });
}
};
从这里修改的拦截器代码
编辑:
你的 html 看起来像:
<input type="text"
data-bind="dateConverter: TestProperty,
dateConverterOptions: { format: 'dd/mm/yyyy', anotherOption: 'example' } " />