knockout.js Custom Bindings Custom text replace binding


This example is a custom binding that replaces text whenever an input value is updated. In this case, spaces will be replaced with "+". It is intended to be used alongside the existing value binding, and shows binding with an object literal.

Sample markup with the replaceText binding:

<input type="text" data-bind="value: myField, replaceText: {value: myField, find:' ', replace:'+'}" />

Custom binding definition:

ko.bindingHandlers.replaceText = {

   //On update, grab the current value and replace text
  'update': function(element, valueAccessor, allBindings, viewModel, bindingContext) {

      //Get the current value of the input 
      var val = ko.utils.unwrapObservable(valueAccessor().value());

      //Replace text using passed in values obtained from valueAccessor()
      //Note - Consider using something like string.js to do the find and replace
      var replacedValue = val.split(valueAccessor().find).join(valueAccessor().replace);

      //Set new value

Sample view model:

var ViewModel = function(){
  var self = this;
  self.myField = ko.observable("this is a simple test");

ko.applyBindings(new ViewModel());