views:

37

answers:

2

I have some in-file actionscript 3.0 code. This code controls a number of elements on it's stage. These elements each have an Over, an Out, and a Click event.

I currently define these event listeners as so:

mc_hotspot.addEventListener(MouseEvent.MOUSE_OVER, lift);
mc_hotspot.addEventListener(MouseEvent.MOUSE_OUT, setDown);
mc_hotspot.addEventListener(MouseEvent.CLICK, select);;
mc_spinspot.addEventListener(MouseEvent.MOUSE_OVER, spinspotOver);
mc_spinspot.addEventListener(MouseEvent.MOUSE_OUT, spinspotOut);
mc_spinspot.addEventListener(MouseEvent.CLICK, spinClick);
mc_spinspot2.addEventListener(MouseEvent.MOUSE_OVER, spinspot2Over);
mc_spinspot2.addEventListener(MouseEvent.MOUSE_OUT, spinspot2Out);
mc_spinspot2.addEventListener(MouseEvent.CLICK, spin2Click);
btn_back.addEventListener(MouseEvent.MOUSE_OVER, backOver);
btn_back.addEventListener(MouseEvent.MOUSE_OUT, backOut);
btn_back.addEventListener(MouseEvent.CLICK, backClick);

As you can see, this is a very long and convoluted way of defining the events for these elements and there is also an event triggered function to go with each of these.

I'll be expanding the project to add three more spinspots and one or two more buttons soon and I was just wondering if there was any other way to define and cater for these events.

In the case of the spinspots all the over and out events are the same but each have their own duplicate function and listener.

Thanks in advance

+2  A: 

You could just build a function like:

function addButtonEvents(mc:*,over:Function,out:Function,click:Function = null) {
    mc.addEventListener(MouseEvent.MOUSE_OVER,over,false,0,true);
    mc.addEventListener(MouseEvent.MOUSE_OUT,out,false,0,true);

    //if we have an optional click event
    if (click != null)
         mc.addEventListener(MouseEvent.CLICK,click,false,0,true);

}

then you can add all three events in one call i.e

addButtonEvents(mc_spinspot, spinspotOver, spinspotOut, spinClick);
Ross
+1  A: 

best way is via encapsulation, ususaly the over and out states only effect the item that is being over or out, therefore you can make a spinspot class and make over and out handlers in that and only worry about the click handler in the parent class.

otherwise you can have one over, out and click handler and then sort the action by target of the event (if (ev.target == mc_spinspot)) etc. doing that you can also have a assignEvents function that gives the over, out and click responders to the passed variable

private function addEvents(obj:Sprite){
    obj.addEventListener(MouseEvent.MOUSE_OVER, overHandler);
    obj.addEventListener(MouseEvent.MOUSE_OUT, outHandler);
    obj.addEventListener(MouseEvent.CLICK, clickHandler);

}
addEvents(mc_spinspot);
shortstick