Based on this answer Knockout.js: time input format and value limitation , I am trying to create a custom binding that sets the observed value to null, if the value is equal to the string is empty, here is the code that does not work, Ip the observed is always zero for the model
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:
<input type="text" data-bind="stringEmptyNull: Ip" />
Model:
var Model = function () {
this.Ip = ko.observable()
ko.applyBindings(this, $myForm[0]);
};
instance = new Model();
source
share