Board index FlightGear Development Canvas

Multiple event listeners from for loop

Canvas is FlightGear's new fully scriptable 2D drawing system that will allow you to easily create new instruments, HUDs and even GUI dialogs and custom GUI widgets, without having to write C++ code and without having to rebuild FlightGear.

Multiple event listeners from for loop

Postby omega95 » Sun Aug 11, 2013 5:36 am

Have a small problem here...

This code is supposed to create a couple of buttons next to some other text (which I didn't include here) and I thought each button will send the function to it's own id, but they all seem to be passing the value of lim.

Code: Select all
for(var i=0; i<lim; i+=1) {
resutls.createChild("text")
   .setText("[Book Flight])
   .setFontSize(18)
   .setFont("Helvetica.txf")
   .setColor(1,1,1)
   .setTranslation(490, 202 + (18*i))
   .addEventListener("click", func(e) {
   bookFlight(i);
}


it seems to be placing the text at different positions according to i just fine though.
Merlion Virtual Airlines - the experience of a flight time...
Get high quality aircraft, airports, video tutorials or development tools from my hangar.
omega95
 
Posts: 1223
Joined: Sat Jul 30, 2011 12:59 am
Location: -unknown-
Callsign: MIA0001, OM-EGA
IRC name: omega95
Version: 2.12 git
OS: Ubuntu 13.04

Re: Multiple event listeners from for loop

Postby Hooray » Sun Aug 11, 2013 5:44 am

your function's callback cannot access the variable later on without first "saving it" inside a closure, see Philosoper's explanation at:

http://wiki.flightgear.org/Using_Nasal_ ... n_closures
viewtopic.php?f=30&t=20492&p=187779&hilit=closure#p187744
Please don't send support requests by PM, instead post your questions on the forum so that all users can contribute and benefit
Thanks & all the best,
Hooray
Help write next month's newsletter !
pui2canvas | MapStructure | Canvas Development | Programming resources
Hooray
 
Posts: 11968
Joined: Tue Mar 25, 2008 8:40 am

Re: Multiple event listeners from for loop

Postby omega95 » Sun Aug 11, 2013 6:26 am

And ofcourse, that worked - I couldn't 'save' the variable but a funciton generator worked fine. :)
Merlion Virtual Airlines - the experience of a flight time...
Get high quality aircraft, airports, video tutorials or development tools from my hangar.
omega95
 
Posts: 1223
Joined: Sat Jul 30, 2011 12:59 am
Location: -unknown-
Callsign: MIA0001, OM-EGA
IRC name: omega95
Version: 2.12 git
OS: Ubuntu 13.04


Return to Canvas

Who is online

Users browsing this forum: No registered users and 1 guest