0

i want to pass a varriable "templateBody " into a function is it possible ? This my code

function GetMenu(){
 var templates = [{name:"maher",body:"<p>Maher test</p>"},{name:"Jeremy",body:"<p>Jeremy test</p>"}]
 var payload = []
 for (var i = 0; i<templates.length; i++){
   var templateBody = templates[i].body
     payload.push({
       text : templates[i].name,
       onclick: function(templateBody){tinymce.activeEditor.execCommand('mceInsertContent', false, templateBody);}
 })
}
return payload
}
Main Flow
  • 319
  • 2
  • 18

2 Answers2

1

You can only pass a variable if you are calling the function. But you are not. However, since all JavaScript functions are closures, you still have access to any variable defined in a higher scope. There is nothing special to do.

The issue with your code is that you are shadowing the variable templateBody with the parameter templateBody. Remove it:

function(templateBody) -> function()

The other issue is that you are creating a function inside a loop. That doesn't work very well with closures, but there are solutions: JavaScript closure inside loops – simple practical example

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

You have:

function(templateBody){
  tinymce.activeEditor.execCommand('mceInsertContent', false, templateBody);
}

Given the name of the property, I expect this is to be called when the onclick event fires. Which will inject the event into the function as templateBody, it won't use the templateBody defined above.

Moreover, the templateBody is being used as a closure inside a loop, which means it won't remain the same for the defined functions. You need a proper closure pattern like this:

(function(templateBody){
  return function() {
    tinymce.activeEditor.execCommand('mceInsertContent', false, templateBody);
  }
})(templateBody);
MinusFour
  • 13,913
  • 3
  • 30
  • 39
  • *"You need a proper closure pattern like this:"* The original function already is a "proper" closure. The solution is to create an additional scope in the loop body, which has nothing to do with closures. – Felix Kling Sep 01 '15 at 14:16
  • It's not a closure that fits the problem, hence not a proper closure. That's what I meant. – MinusFour Sep 01 '15 at 14:17