Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 241
Seiyria Avatar asked Dec 06 '22 02:12

Seiyria


1 Answers

taking some other answers and making them work for the current version of summernote I've made the following:

Something to note: this bindinghandler accomodates inbound changes from the viewModel as well.

 ko.bindingHandlers.wysiwyg = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var value = ko.unwrap(valueAccessor());
        var allBindings = ko.unwrap(allBindingsAccessor())
        var optionsBinding = allBindings.wysiwygOptions || {};
        var $element = $(element);
        var options = $.extend({}, optionsBinding);

        var updateObservable = function (e) {
            valueAccessor($element.summernote('code'));
            return true;
        };

        options.callbacks = {};
        options.callbacks.onKeyup = options.callbacks.onFocus = options.callbacks.onBlur = updateObservable;

        $element.html(value).summernote(options);
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var value = ko.unwrap(valueAccessor());
        $(element).summernote('code', value);
    }
};

A few options have changed and you don't have to investigate event dom data. Also I don't need to update on both keyDown and keyUp so my list of events are a bit different. And my binding handler isn't "summernote" in order to make this more flexible to be changed out in the future. it's just wysiwyg. YMMV

like image 121
22 revs, 15 users 88% Avatar answered Mar 13 '23 08:03

22 revs, 15 users 88%