knockout binding handler for jwysiwyg textarea

1.8k Views Asked by At

So I noticed knockout js doesn't play well with jQuery jwysiwyg plugin.

After reading this blog post: http://www.knockmeout.net/2011/07/another-look-at-custom-bindings-for.html And this SO answer: How to detect a change with jQuery to the contents of a textarea that's using jWYSIWYG plugin?

I wrote the following binding handler:

    ko.bindingHandlers.wysiwyg = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var options = allBindingsAccessor().wysiwygOptions || {};
        var value = ko.utils.unwrapObservable(valueAccessor());
        var $e = $(element);
        $.extend(true, {
            initialContent : value
        }, options);

        $e.wysiwyg(options);

        //handle the field changing
        function detectFn() {
            var observable = valueAccessor();
            var newvalue = $e.wysiwyg("getContent");
            observable(newvalue);
        }

        var current = $e.wysiwyg('document');
        var timer;
        current.bind({    
            keyup: function(){
                clearTimeout(timer);
                timer = setTimeout(detectFn, 1000);
            }
        });

        //handle disposal (if KO removes by the template binding)
        ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
            $e.wysiwyg('destroy');
        });
    },
    update: function (element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        $(element).wysiwyg("setContent", value);
        ko.bindingHandlers.value.update(element, valueAccessor);
    }
};

use like this:

<textarea data-bind="wysiwyg: yourViewModelValue"></textarea>

so far it's working for me, any comments will be appreciated.

I think this can be of use for anyone looking into getting kockout js and jwysiwyg working together on binding the textarea element.

0

There are 0 best solutions below