Knockout valueUpdate to work with editable div elements
Asked Answered
P

1

7

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/

Polythene answered 21/8, 2013 at 7:55 Comment(1)
can you please post a jsfiddle example?Byrnes
B
8

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/

Bondswoman answered 21/8, 2013 at 12:54 Comment(2)
This doesnt seem to work with IE if you update the content in any other way other than key up. For instance, Im using execCommand to create links in the editable div, but unfortunately this doesnt then update the values. Im currently looking for a way around this without manually binding the content again.Notarize
Using focus on the event handler seems to fix it. ko.utils.registerEventHandler(element, "focus", updateHandler);Notarize

© 2022 - 2024 — McMap. All rights reserved.