Automatically trim whitespace from all observable values
knockout.js
Solution
I had the same problem. I wrote an extension so you can call `trimmed` in your view-model without having to change your bindings. For example:
var vm = {
myValue: ko.observable('').trimmed()
}
The extension:
ko.subscribable.fn.trimmed = function() {
return ko.computed({
read: function() {
return this().trim();
},
write: function(value) {
this(value.trim());
this.valueHasMutated();
},
owner: this
});
};
Code is on JSFiddle with examples.
Problem
I have a ViewModel in Knockout that is derived mainly from the mapping plugin (ie, dynamically). This works fine. However, now my client wants me to make sure that all inputs have whitespace trimmed off before submitting to the server. Obviously, the trimming code is very simple, but being relatively new to Knockout, I'm not sure exactly where to put this code. I read about extenders, but that seems pretty verbose and repetitive to go back and add that to each observable. Plus I'm not even sure I can do that to dynamically generated observables (a la, the mapping plugin). Is there any central mechanism I can extend/override where I can inject some trimming code every time an observable changes? Basically I'm trying to avoid hours spent going through all of our forms and adding special binding syntax in the HTML if I don't have to. Thanks.