actionscript 3 - Actionscript3: add and remove EventListeners (with dynamic name and dynamic variables) -


picture: http://yfrog.com/1rcheckerboardflashvraagjg

hey all!

  • i making boardgame in flash action script 3
  • each position on board buttons this: button_1_1, button_1_2 etc.
  • whenever character selected want move script has add event listeners positions around selected unit
 // function adds or deletes event listener function listentobutton (istrue:int, position_x:int, position_y:int):void {     var myfunction:function = new function;     myfunction = function ():void {userclickedposition(position_x, position_y)};     if (istrue == 1) {         this["button_position_"+(position_x)+"_"+(position_y)].addeventlistener(mouseevent.click, myfunction);     } else {         this["button_position_"+(position_x)+"_"+(position_y)].removeeventlistener(mouseevent.click, myfunction);     } } 

in rest of code have:

  • function userclickedposition(position_x:int, position_y:int)
    selects or deselect unit

  • function selectunit(position_x:int, position_y:int):
    uses listentobutton(1) function add 8 listeners (the positions around clicked unit)

  • function deselectunit(position_x:int, position_y:int):
    uses listentobutton(0) function delete 8 listeners (the positions around clicked unit)

my question: adding eventlisteners no problem removing them dont seem work? did wrong?

when go remove event, using new instance of myfunction, not same 1 added with. either need declare function other function, , use event args examine button's position like. think want stagex , stagey properties: http://www.adobe.com/livedocs/flex/3/langref/flash/events/mouseevent.html

// function adds or deletes event listener function listentobutton (istrue:int, position_x:int, position_y:int):void {     if (istrue == 1) {         this["button_position_"+(position_x)+"_"+(position_y)].addeventlistener(mouseevent.click, myfunction);     } else {         this["button_position_"+(position_x)+"_"+(position_y)].removeeventlistener(mouseevent.click, myfunction);     } }  function myfunction(eventarg:mouseevent):void { //use mouseevent }; 

or can create little myfunctionparameters class hold coordinate information , create new instance of class, add collection indexed x , y coordinates, , later when go remove event, lookup myspaceparameters instance in collection, based on x , y coordinates, use remove function.

class myfunctionparameters { public x:int; public y:int;     function myfunction(eventarg:mouseevent):void {         userclickedposition(x,y);     }; } 

Comments

Popular posts from this blog

ruby - When to use an ORM (Sequel, Datamapper, AR, etc.) vs. pure SQL for querying -

php - PHPDoc: @return void necessary? -

c++ - Convert big endian to little endian when reading from a binary file -