Skip to main content
Inspiring
January 24, 2013
Answered

Pass a function when calling onClick for a button (UI)

  • January 24, 2013
  • 1 reply
  • 2575 views

Hi

I´m now studying and adventuring myself in the Script UI creation. I´m enjoying it !!!

I´m having the following trouble: I added a button to a dialog box and would like to tell script to run some commands when users click on the button. So this is a simple (poor example):

var dlg = new Window ("dialog", "My dialog", [0,0,0,0])

dlg.size = [500,500]

dlg.location = [300,300]

var b = dlg.add("button", [0,0,0,0], "Run")

b.location = [20, 180]

b.size = [80, 30]

dlg.show()

b.onClick = test () //the problem is here

function test(){

  alert("teste")

}

-------

Everything is right. But the onClick event does not execute the function test I´m passing! What Am I missing?

I know if I use

b.onClick = function (){

...

}

It works...but I´d like the function to be called instead of directlly created when calling the onClick. Do not know if I´m able to explain it better.

Thank you for the help

Best Regards

Gustavo.

This topic has been closed for replies.
Correct answer Paul Riggott

The norm would be ...

var dlg = new Window ("dialog", "My dialog", [0,0,0,0])
dlg.size = [500,500]
dlg.location = [300,300]
var b = dlg.add("button", [0,0,0,0], "Run")
b.location = [20, 180]
b.size = [80, 30]
b.onClick = function(){ //the problem is here
test();
}
dlg.show()

function test(){
  alert("teste")
}

1 reply

Inspiring
January 24, 2013

P.S: the way I wrote my example....function will execute when I close the dlg dialog.

And if I write the function at beggining it will autoexecute before dialog box be showed.

Looks it´s running the function automatically in the sequence of the commands! Not what I expect to be.

Thank you a lot

Gustavo.

Paul Riggott
Paul RiggottCorrect answer
Inspiring
January 24, 2013

The norm would be ...

var dlg = new Window ("dialog", "My dialog", [0,0,0,0])
dlg.size = [500,500]
dlg.location = [300,300]
var b = dlg.add("button", [0,0,0,0], "Run")
b.location = [20, 180]
b.size = [80, 30]
b.onClick = function(){ //the problem is here
test();
}
dlg.show()

function test(){
  alert("teste")
}

Inspiring
January 24, 2013

Hi Paul

Interesting. So EVERY onClick, onClose, onOpen, onChange ... events must receive a function??

And sure we can call other functions inside them.

Thank you a lot

Gustavo.