Introduction
In web applications, when we are working with form inputs; sometimes we have to trim the user input values to avoid unnecessary white spaces. So every input value needs to be trimmed and use of so many $.trim()
comes ahead.
Background
As the number of input grows, so does the use of $.trim()
. And try to imagine doing the same thing in every form. To avoid such massive use of $.trim()
, we can use custom knockout value binding handler which will ensure that if the user inputs/server send the value with unnecessary white spaces, it would be trimmed and will be reassigned to the input field.
Custom Binding Handler
Here is the custom binding handler which will help use in trimmed value binding:
ko.bindingHandlers.trimedValue = {
init: function (element, valueAccessor, allBindingsAccessor) {
$(element).on("change", function () {
var observable = valueAccessor();
var trimedValue = $.trim($(this).val());
observable($(this).val());
observable(trimedValue);
});
},
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
var trimedValue = $.trim(value);
$(element).val(trimedValue);
}
};
Using The Handler In HTML
We are going to use the handler like this. It's really important to remember to use data-bind="trimedValue: "
rather than data-bind="value: "
<h2>Trimed value building</h2>
<div>
<span>change the values to see if triming is taking place or not</span>
<!--
<div>
<label>First Name</label>
<input type="text" data-bind="trimedValue: firstName" />
</div>
<!--
<div>
<label>Last Name</label>
<input type="text" data-bind="trimedValue: lastName" />
</div>
<!--
<div>
<label>Age</label>
<input type="text" data-bind="trimedValue: age" />
</div>
</div>
View Model
Now let's see the view model:
function ViewModel() {
var self = this;
self.firstName = ko.observable('');
self.lastName = ko.observable('');
self.age = ko.observable(0);
self.init = function () {
self.firstName(' Dipon ');
self.lastName(' Roy ');
self.age(' 24 ');
};
}
Finally, apply view model binding:
$(document).ready(function () {
var vm = new ViewModel();
vm.init();
ko.applyBindings(vm);
});
Find the JsFiddel example at http://jsfiddle.net/DiponRoy/Ygey4/2/.