Adding onclick function to a generated button

Find out why the . goes before the /

Moderator: Paul Tuersley

Post Reply
MuffinDude
Posts: 2
Joined: October 26th, 2017, 1:07 pm

October 26th, 2017, 1:22 pm

Hello,
I'm having problems adding functions to newly generated buttons 

Code: Select all

for(i = 0; i < files.length; i++){
  var buttonX = mainWindow.add("button", undefined, presets[i]);
  buttonX.onClick = function(){
    mainLayer.applyPreset(presets[i]);
  }
};
It's looping through all the presets in the folder and generating a button for each of them.
I want that when you click on the button, the preset is applied to the layer.
But how can I make it so that each button has a unique function because right now everything is getting the same function.

Cheers
jordanwade33
Posts: 14
Joined: December 8th, 2014, 11:11 pm

November 1st, 2017, 1:15 pm

I recently worked on a script that had a similar issue and this is how I worked around it. I'm sure there's probably a better way to do it that this, but I just use a separate function that gets assigned to every button and then assign the number in the preset array to the button name, so when the button gets clicked, it can retrieve the right position in the array to use the right preset. Hopefully that makes sense.

Code: Select all

for(i = 0; i < files.length; i++){
  var buttonX = mainWindow.add("button", undefined, presets[i]);
  buttonX.name = i;
  buttonX.onClick = applyMyPreset;
  }


function applyMyPreset(){
  mainLayer.applyPreset(presets[this.name]);
}
MuffinDude
Posts: 2
Joined: October 26th, 2017, 1:07 pm

November 2nd, 2017, 1:21 pm

Thank you so much for your response. Works like a charm!
Post Reply