tags:

views:

72

answers:

1

I created a SplitButton in TinyMCE and I am using a for loop to add buttons, but for some reason the buttons' onclick is always calling the same one (the last from the for loop). It seems every time I add a menu option, the callback is being 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]);
    }});
}

});

The menus are created correctly, but for example if I select 'Options 1' and select any option, tinyMCE will print the last option from that subMenu. I don't know how to fix this.

+1  A: 

I fixed it, so I'll answer my own question. I needed to use closures in a special way. 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], variable});
}
Rocket