7
votes

I am using bootstrap wysiwyg editor to replace the textarea that is being databinded to a observable value from viewModel.

<textarea data-bind="html:data, valueUpdate:'afterkeydown'"></textarea>

The above textarea updates the corresponding viewModel value everytime a key is pressed from inside the textarea.

Now the text area is replaced by wysiwyg bootstrap editor

<div class="editor" data-bind="html:data, valueUpdate:'afterkeydown'"></div>

Now the the observable is not updated on keydown.

any idea how to make this work?

Creating a custom bindinghandler "htmlUpdate" to div tags, similar to valueUpdate that is working with input elements?

also that should support inline HTML, Any ideas about how to reuse the "valueUpdate" to work with div elements?

Here is the fiddle http://jsfiddle.net/cHTCq/

1
can you please post a jsfiddle example? - ebram khalil

1 Answers

8
votes

Here is a simple binding to work with a contentEditable div like that and have it update as you type as well as when you click the formatting buttons:

ko.bindingHandlers.htmlValue = {
    init: function(element, valueAccessor, allBindingsAccessor) {
        var updateHandler = function() {
            var modelValue = valueAccessor(),
                elementValue = element.innerHTML;

            //update the value on keyup
            modelValue(elementValue);
        };

        ko.utils.registerEventHandler(element, "keyup", updateHandler);
        ko.utils.registerEventHandler(element, "input", updateHandler);
    },
    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor()) || "",
            current = element.innerHTML;

        if (value !== current) {
            element.innerHTML = value;    
        }
    }
};

Here is your fiddle updated to use it: http://jsfiddle.net/rniemeyer/hp3K6/