Question

First up: check this fiddle.

I have sortable array of elements created with the Knockout sortable library. When I initially apply the binding the cleditor initializes fine.

However, when sortable elements are sorted, the cleditor fails to re-initialize (I'm not sure what happens but cleditor fails). The cleditor just displays "true" instead of actual value in Firefox, and nothing in all other browsers.

I'm trying to figure out where the problem is, whether it is on the custom binding, or jQuery-UI, or the Knockout sortable library?

I am not recieving any errors in my console.

ko.bindingHandlers.cleditor = {
        init: function(element, valueAccessor, allBindingsAccessor) {

            var modelValue = valueAccessor(),
                allBindings = allBindingsAccessor();

            var $editor = jQuery(element).cleditor({
                height: 50,
                controls: "bold italic underline | bullets numbering | undo redo"
            });

            $editor[0].change(function() {

                var elementValue = $editor[0].doc.body.innerHTML;
                if (ko.isWriteableObservable(modelValue)) {
                    modelValue(elementValue);

                } else {
                    if (allBindings['_ko_property_writers'] && allBindings['_ko_property_writers'].cleditor) {
                        allBindings['_ko_property_writers'].cleditor(elementValue);
                    }
                }
            });
        },

        update: function(element, valueAccessor) {
            var value = ko.utils.unwrapObservable(valueAccessor()) || '',
                $editor = jQuery(element).cleditor();

            if ($editor[0].doc.body.innerHTML !== value) {
                //$editor[0].doc.body.innerHTML = value;
                $editor[0].doc.body.innerHTML = value;
                $editor[0].focus();
            }
        }
    };

How can I make the cleditor to work, even after the elements are sorted?

I found this resource, but I couldn't find anything wrong in code as said in that topic.

Was it helpful?

Solution

The link you provided was helpful. The CLEditor refresh method is the right way to update it after it's dragged. It just needs to be done at the correct time, using the sortable stop event.

stop: function(event, ui) {
    $(ui.item).find("textarea").cleditor()[0].refresh();
}

http://jsfiddle.net/mbest/rh8c2/1/

I also worked to integrate this into your cleditor binding. In the init function:

jQuery(document).on('sortstop', function(event, ui) {
    if (jQuery.contains(ui.item[0], element)) {
        jQuery(element).cleditor()[0].refresh();
    }
});

I also made a change in the update function to keep the <textarea> value in sync, because refresh updates the editor's value from the <textarea>:

$editor[0].updateTextArea();

http://jsfiddle.net/mbest/jw7Je/7/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top