knockout contentEditable binding

前端 未结 3 1350
再見小時候
再見小時候 2020-12-24 09:50

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

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-24 09:52

    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.

提交回复
热议问题