Search code examples
knockout.jssummernote

knockout and summernote not working


So I'm trying to get knockout to play nicely with summernote and it's not really working. I realized this is because summernote uses a <div contenteditable> and not just an input field.

My binding is this:

ko.bindingHandlers.summernote = {
    init: function (element, valueAccessor) {
        var options = valueAccessor();
        $(element).summernote(options);
    }
};

Obviously knockout doesn't work too well with just a contenteditable, so what can I do?


Solution

  • I actually began to think about this a bit more and decided to post my own solution since there wasn't really anything else on google. All I did was change the above binding to be like so:

    ko.bindingHandlers.summernote = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var options = valueAccessor();
            var binding = ko.utils.unwrapObservable(allBindingsAccessor()).value;
    
            var updateObservable = function(e) {
                binding(e.currentTarget.innerHTML);
            };
    
            options.onkeydown = options.onkeyup = options.onfocus = options.onblur = updateObservable;
    
            $(element).summernote(options);
        }
    };
    

    Just watching the blur / focus / keypress / keyrelease events was sufficient to update the observables. It's not perfect, but it works.