I'm having a string that contains many editable region, please consider this string
var str = "Regular ... are patterns used to match character .... in strings. In ..., regular expressions are also objects."
editable regions are contains ('...'), I want to make that places editable. means i want inject a editable content inside that string. I would like to use knockout for this purpose. I've referred the niemeyer's about content editable using knockout. can anyone suggest me a better way to achieve this. this my code here
ko.bindingHandlers.editableContent = {
init: function(element, valueAccessor, allBindingsAccessor) {
$(element).css({ "background-color": "#ff77ee", "margin-left": "-2px", "letter-spacing": "0.05"});
ko.utils.registerEventHandler(element, "keyup", function() {
var modelValue = valueAccessor();
var elementValue = element.innerHTML;
if (ko.isWriteableObservable(modelValue)) {
modelValue(elementValue);
}
else { //handle non-observable one-way binding
var allBindings = allBindingsAccessor();
if (allBindings['_ko_property_writers'] && allBindings['_ko_property_writers'].editableContent) allBindings['_ko_property_writers'].editableContent(elementValue);
}
})
},
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor()) || "";
element.innerHTML = value;
}
};
ko.bindingHandlers.myBinding = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var div = document.createElement("div");
var fulltext = valueAccessor();
element.appendChild(div);
div.innerHTML = fulltext().replace(/\.\.\./g, "<span data-bind = 'editableContent : editedText' contenteditable='true'></span>");
ko.applyBindings(viewModel,div);
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
}
};
$(document).ready(function () {
var viewModel = function () {
var self = this;
self.fullText = ko.observable('Regular ... are patterns used to match character .... in strings. In ..., regular expressions are also objects.');
self.editedText = ko.observable('...');
}
ko.applyBindings(new viewModel());
});