Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout content editable custom binding

Why in this example http://jsfiddle.net/JksKx/8/ div lost cursor when i write text? How to fix such behavior?

like image 605
Neir0 Avatar asked Oct 26 '11 14:10

Neir0


2 Answers

The keyup event is firing and writing to your viewmodel, which then triggers the update function of the custom binding. This is writing the innerHTML back to the element, which is causing you to lose focus.

An easy fix is to check in the update function if the element.innerHTML already is the same as the value that you want to set it to.

http://jsfiddle.net/rniemeyer/JksKx/9/

ko.bindingHandlers.htmlValue = {
    init: function(element, valueAccessor, allBindingsAccessor) {
        ko.utils.registerEventHandler(element, "keydown", 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'].htmlValue) allBindings['_ko_property_writers'].htmlValue(elementValue);
            }
        }
                                     )
    },
    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor()) || "";
        if (element.innerHTML !== value) {
            element.innerHTML = value;
        }
    }
};
like image 158
RP Niemeyer Avatar answered Nov 04 '22 04:11

RP Niemeyer


might want to change keydown to keyup, but other than that works really well =)

ko.utils.registerEventHandler(element, "keyup", function() {
like image 30
Hanns Avatar answered Nov 04 '22 04:11

Hanns