基于这个答案Knockout.js: time input format and value constraint,我正在尝试创建一个自定义绑定,如果值为空字符串,则将 observable 设置为 null,这是不起作用的代码,Ip observable 始终为 null模型
ko.bindingHandlers.stringEmptyNull = {
init: function (element, valueAccessor, allBindingsAccessor) {
var underlyingObservable = valueAccessor();
var interceptor = ko.dependentObservable({
read: underlyingObservable,
write: function (value) {
if (value != null && value.trim() == '')
underlyingObservable();
}
});
ko.bindingHandlers.value.init(element, function () { return interceptor }, allBindingsAccessor);
},
update: ko.bindingHandlers.value.update
};
输入:
<input type="text" data-bind="stringEmptyNull: Ip" />
模型:
var Model = function () {
this.Ip = ko.observable()
ko.applyBindings(this, $myForm[0]);
};
instance = new Model();