Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass parameter from a dynamic created dijit button onClick?

Tags:

dojo

I wonder, can I pass parameter from a dynamic created dijit button ?

function testcallfromDynamicButton (value) {
   alert(value);
}

var thisButton = new dijit.form.Button({
label : thelineindex ,
id : "I_del_butt"+thelineindex,
name : "I_del_butt"+thelineindex,
onClick : testcallfromDynamicButton('test')
}).placeAt( thetabletd1 ) ;

Seems , this dosen't work, I tried to change to this. It works !!

function testcallfromDynamicButton () {
alert('test');
}

var thisButton = new dijit.form.Button({
  label : thelineindex ,
  id : "I_del_butt"+thelineindex,
  name : "I_del_butt"+thelineindex,
  onClick : testcallfromDynamicButton
}).placeAt( thetabletd1 ) ;

The question is , I want to let the function know, which button has been clicked (as all buttons are dynamically created, and the button id is generate by indexnumber), so I need to pass the button itself's id to the function. But passing parameter through onClick call seems not work in Dijit . How can I make it work ?

like image 727
Colacat Avatar asked Feb 24 '23 03:02

Colacat


1 Answers

No worries, this is a very common Javascript mistake - in fact, it has nothing to do with Dojo.

onClick expects a function object, but you are actually executing testcallfromDynamicButton('test') and assigning the result from this function call to it. For example, if testcallfromDynamicButton returned "colacat", the onClick event would be given that string! That's obviously not what you want.

So we need to make sure onClick is given a function object, like you do in your second example. But we also want to give that function an argument when it's executed. The way to do this is to wrap your function call in an anonymous function, like so:

var thisButton = new dijit.form.Button({
  label : thelineindex ,
  id : "I_del_butt"+thelineindex,
  name : "I_del_butt"+thelineindex,
  onClick : function() {
    testcallfromDynamicButton('test');
  }
}).placeAt( thetabletd1 ) ;

This way, onClick gets a function object, and testcallfromDynamicButton is executed with an argument.

like image 115
Frode Avatar answered Apr 27 '23 12:04

Frode