自定义文本替换绑定
此示例是一个自定义绑定,可在更新输入值时替换文本。在这种情况下,空格将替换为“+”。它旨在与现有值绑定一起使用,并显示与对象文字的绑定。
使用 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());