tiff / wysihtml5

Open source rich text editor based on HTML5 and the progressive-enhancement approach. Uses a sophisticated security concept and aims to generate fully valid HTML5 markup by preventing unmaintainable tag soups and inline styles.
http://xing.github.com/wysihtml5/
MIT License
6.5k stars 1k forks source link

Integrate wysithtml5 with knockout.validation. #444

Open jmogera opened 10 years ago

jmogera commented 10 years ago

I am trying to integrate wysithtml5 control with knockout.validation, but it doesn't seem to work.

I have posted the issue on stackoverflow and the suggested solution doesn't work. http://stackoverflow.com/questions/19276890/bootstrap-wysihtml5-knockout-validation/19279403?noredirect=1#19279403

what is the best way to set this up?

dmr commented 10 years ago

From my experience the best way is to create a custom bindingHandler, here is what we came up with:

ko.bindingHandlers.wysiwyg = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var value_observable = valueAccessor();
        var options = {
            'events': {
                'load': function() {
                    var editor = this;
                    editor.loaded = true;
                    editor.initial_value = editor.getValue();
                    editor.value_edited = false;
                    $(editor.composer.element).on('keyup', function() {
                        var value = editor.getValue();
                        if (editor.initial_value === value &&
                            !editor.value_edited) {
                            return;
                        }
                        if(value_observable() === value) {
                            return;
                        }
                        value_observable(value);
                        editor.value_edited = true;
                    });
                },
                'aftercommand:composer': function() {
                    var editor = this;
                    var value = editor.getValue();
                    if (this.loaded === true && editor.initial_value !== value && value_observable() !== value) {
                        value_observable(value);
                    }
                }
            }
        };
        $(element).wysihtml5(options);
    }
};
dmr commented 10 years ago

Initialize the binding with a form field and ko.validation will work as expected. In the Viewmodel:

this.form = ko.validatedObservable({'content': ko.observable().extend({'required': true})});

The Html:

<textarea data-bind="wysiwyg: form().content"></textearea>