6

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.

Community
  • 1
  • 1
Remco Ros
  • 1,467
  • 15
  • 31
  • Nice binding but this isn't really a question. You should post this on the KO google group if you haven't already. – madcapnmckay Feb 22 '12 at 22:14
  • Thanks for the info, but this is *not exactly* how we do things here. If you would, [edit] to make this a question, then flag to have it reopened (say that I suggested this in the flag!). You can then add an answer detailing your solution. After two days, you can select it as correct and close the question out. It may feel odd, but that is the accepted way of sharing information here. Thanks. –  Feb 23 '12 at 17:19
  • Hi, Seems to work one way but when I change the value in the textarea through jwysiwyg the value knockout has doesn't, any clues as to how to get the two to sync? – Phil May 25 '12 at 10:16
  • Great binding, helped me with markitup another jquery editor. Shame its closed as I could have posted my binding as well. Pretty stupid that it isn't exactly what we do here because I'm sure it would be helpful. – rball Jul 27 '12 at 18:42

0 Answers0