Binding knockout with tinymce

2019-07-15 15:33发布

问题:

I am trying to use knockout 3.0.0 with tinymce 4.0.18.

I want to create something like this: few editable elements (3 here) but these elements are taken from knockout. Doing this without tinyMCE is not a problem (here is my attempt).

But when I try to achieve the same result with tinyMCE by doing something like this:

function ViewModel() {
    var self = this;
    self.editableAreas = ko.observableArray([{
        id : 1,
        txt: ko.observable('first text area'),
    },{
        id : 2,
        txt: ko.observable('second text area'),
    },{
        id : 3,
        txt: ko.observable('all observable text area'),
    }]);
}

ko.applyBindings(new ViewModel());

tinymce.init({
    selector: "div.editableArea",
    schema: "html5",
    inline: true,
    toolbar: "bold italic underscore",
    menubar: false
});

Googling a little big I have found two custom bindings for tinyMCE (first binding and second). Is this the best approach and how can I modify my fiddle to work as intended?

回答1:

Using a bindingHandler for binding DOM elements to the viewmodel is the "correct" way. Just include one of the bindingHandlers you linked to. I updated your jsfiddle using the second bindingHandler (chosen at random since I have no preference, since I don't know of any of them). After including that bindingHandler (and jquery and the jquery.tinymce.min.js which it seems dependent on) I updated the html to the following, in order to use the bindingHandler:

<div data-bind="foreach: editableAreas">
    <div class="editableArea" data-bind="wysiwyg: txt, wysiwygConfig: {    
        schema: 'html5',
        inline: true,
        toolbar: 'bold italic underscore',
        menubar: false
    } "></div>
</div>

In this case I have the tinymce configuration in the view. If you want to have it as a property in your viewModel it should be pretty easy to change it (for example with the following code)