Reputation: 23
This has been bugging me for a few days now. I have written a multi-functional messageBox class, and it works pretty well, but there's one thing I'm stuck on. First, though, here's some code:
in the document class I have:
var tMsg:Msg = new Msg("Test Message", "This is a test Message", Msg.INPUT);
tMsg.addEventListener('Answered', qa, false, 0, true);
function qa(e:Event):void{
trace(e.target.label,e.target.result);
tLabel.label = e.target.result;
}
When either the 'cancel' or 'ok' buttons are clicked, the result property is set and the 'Answered' event is dispatched. Since this event listener will always need to be added, I thought it would be better to include it within the class constructor; however, each instance of the Msg class would need its own callback, depending on what the result is being used for. Also, the callback functions should be declared in the document class.
I thought this could be accomplished by simply passing the function to the Msg class constructor, and then use that reference to generate the addEventListener dynamically. For example:
/// in document class
var tMsg:Msg = new Msg("Test Message", "This is a test Message", Msg.INPUT, qa);
function qa(e:Event):void{
trace(e.target.label,e.target.result);
tLabel.label = e.target.result;
}
/// in Msg class
public function Msg(txt:String='', msg:String='', type:String=ALERT, callback:Object=null) {
_callback = callback;
addEventListener(Event.ADDED, setup, false, 0, true);
}
private function setup(e:Event){
stage.addEventListener('Answered', _callback, false, 0, true);
}
This doesn't work. I don't know if it's because I'm trying to store the callback reference (the event listener should be added to the stage object) or what? The upside to getting this to work would be I wouldn't have to add an event listener each time I create a new message, just pass along the associated function.
Thank you in advance for any help you could provide me.
Upvotes: 2
Views: 1345
Reputation: 660
You should add the event listener to the object that dispatches the event. If that object isn't on the display list or the event doesn't bubble then the stage will not receive the event.
Upvotes: 2