All menu items in TinyMCE SplitButton using the same callback

I created a SplitButton in TinyMCE and I use the for loop to add buttons, but for some reason the onclick buttons always call the same one (the last of the for loop). It seems that every time I add a menu option, the callback is overwritten.

Let me describe what I mean.

var c = cm.createSplitButton('optionsList', {
title : 'Options',
});

c.onRenderMenu.add(function(c, m){
var Opts1 = options[0];
var Opts2 = options[1];
var Opts3 = options[2];

var sub1 = m.addMenu({title: "Options 1"});
for(var x in Opts1){
    sub1.add({title: Opts1[x], onclick: function(){
        tinyMCE.activeEditor.execCommand('mceInsertContent',false,Opts1[x]);
    }});
}

var sub2 = m.addMenu({title: "Options 2"});
for(var y in Opts2){
    sub2.add({title: Opts2[y], onclick: function(){
        tinyMCE.activeEditor.execCommand('mceInsertContent',false,Opts2[y]);
    }});
}

var sub3 = m.addMenu({title: "Options 3"});
for(var z in Opts3){
    sub3.add({title: Opts3[z], onclick: function(){
        tinyMCE.activeEditor.execCommand('mceInsertContent',false,Opts3[z]);
    }});
}

});

Menus are created correctly, but, for example, if I select "Options 1" and select any option, tinyMCE will display the last option from this submenu. I do not know how to fix this.

+3
source share
1 answer

I fixed it, so I will answer my question. I needed to use closure. The solution was:

var insertVar = function(val){
    return function(){tinyMCE.activeEditor.execCommand('mceInsertContent',false,val);}
};

var sub1 = m.addMenu({title: "Options 1"});
for(var x in Opts1){
    var variable = insertVar(Opts1[x]);
    sub1.add({title: Opts1[x], onclick: variable});
}
+5
source

Source: https://habr.com/ru/post/1755580/


All Articles