在TinyMCE中初始化后修改工具栏的正确方法

aar*_*ard 7 javascript jquery tinymce tinymce-4

我正在使用javascript扩展云托管的LMS.因此,我们可以向页面添加javascript,但不能修改不同组件的供应商javascript.

LMS经常使用tinyMCE.目标是在每个tinyMCE编辑器的工具栏上添加一个新按钮.

问题是,由于tinyMCE模块是在供应商的不可触摸的代码中初始化的,我们无法修改init()调用.因此,我们无法将任何文本添加到init()对象的"toolbar"属性中.

所以我以适度的hacky方式完成了这个:

tinyMCE.on('AddEditor', function(e){
  e.editor.on('init', function(){
    tinyMCE.ui.Factory.create({
      type: 'button',
      icon: 'icon'
    }).on('click', function(){
      // button pressing logic
    })
    .renderTo($(e.editor.editorContainer).find('.mce-container-body .mce-toolbar:last .mce-btn-group > div')[0])
  });
});
Run Code Online (Sandbox Code Playgroud)

所以这是有效的,但不用说,我不太愿意在DOM中寻找像插入按钮那样的特定位置.虽然这有效,但我不认为创作者的意图是这样使用它.

如果我们无法修改初始化代码,是否有正确的方法将按钮添加到工具栏中?

Sid*_*dex 13

我找到了一个更优雅的解决方案,但它仍然感觉有点像黑客.这是我得到的:

// get an instance of the editor
var editor=tinymce.activeEditor; //or tinymce.editors[0], or loop, whatever

//add a button to the editor buttons
editor.addButton('mysecondbutton', {
  text: 'My second button',
  icon: false,
  onclick: function () {
    editor.insertContent('&nbsp;<b>It\'s my second button!</b>&nbsp;');
  }
});

//the button now becomes
var button=editor.buttons['mysecondbutton'];

//find the buttongroup in the toolbar found in the panel of the theme
var bg=editor.theme.panel.find('toolbar buttongroup')[0];

//without this, the buttons look weird after that
bg._lastRepaintRect=bg._layoutRect;

//append the button to the group
bg.append(button);
Run Code Online (Sandbox Code Playgroud)

我觉得应该有比这更好的东西,但我没有找到它.

其他说明:

  • _lastRepaintRect因为该repaint 方法需要丑陋,这使得按钮看起来很丑,无论你是否添加新的控件
  • 在代码中查看,没有方法可以在没有重新绘制的情况下向工具栏添加新控件,没有丑陋的黑客就无法绕过它
  • append(b) 相当于 add(b).renderNew()
  • 您可以使用以下代码添加没有黑客的按钮,但您正在短路许多其他东西:

码:

bg.add(button);
var buttonElement=bg.items().filter(function(i) { return i.settings.text==button.text; })[0];
var bgElement=bg.getEl('body');
buttonElement.renderTo(bgElement);
Run Code Online (Sandbox Code Playgroud)