I\'ve written a custom binding handler that toggles whether or not an element is contentEditable. I also want any html bindings to update when the element\'s contents are e
ko.bindingHandlers.htmlLazy = {
update: function (element, valueAccessor) {
var value = ko.unwrap(valueAccessor());
if (!element.isContentEditable) {
element.innerHTML = value;
}
}
};
ko.bindingHandlers.contentEditable = {
init: function (element, valueAccessor, allBindingsAccessor) {
var value = ko.unwrap(valueAccessor()),
htmlLazy = allBindingsAccessor().htmlLazy;
$(element).on("input", function () {
if (this.isContentEditable && ko.isWriteableObservable(htmlLazy)) {
htmlLazy(this.innerHTML);
}
});
},
update: function (element, valueAccessor) {
var value = ko.unwrap(valueAccessor());
element.contentEditable = value;
if (!element.isContentEditable) {
$(element).trigger("input");
}
}
};
var viewModel = {
editable: ko.observable(false),
content: ko.observable("This is the initial content!")
};
ko.applyBindings(viewModel);
do the trick with minimal change. See http://jsfiddle.net/93eEr/3/
You could call the binding handler htmlEditable, maybe that's better than calling it "lazy". Up to you.
Note that the "input" event does not really need to be unbound every time. It won't fire anyway when the element is not contenteditable.