自定義文字替換繫結

此示例是一個自定義繫結,可在更新輸入值時替換文字。在這種情況下,空格將替換為“+”。它旨在與現有值繫結一起使用,並顯示與物件文字的繫結。

使用 replaceText 繫結的示例標記:

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

自定義繫結定義:

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
      valueAccessor().value(replacedValue);
  }
}

示例檢視模型:

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

ko.applyBindings(new ViewModel());