Page 1 of 1

Adding onclick function to a generated button

Posted: October 26th, 2017, 1:22 pm
by MuffinDude
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

Re: Adding onclick function to a generated button

Posted: November 1st, 2017, 1:15 pm
by jordanwade33
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]);
}

Re: Adding onclick function to a generated button

Posted: November 2nd, 2017, 1:21 pm
by MuffinDude
Thank you so much for your response. Works like a charm!