I’m wondering what would be considered best practise for this. It’s fairly inconsequential but I’m interested in peoples opinions.
We have two classes – TitleBar and TemplateMain. TitleBar is a bar at the top of the screen that displays the project title and several buttons (settings, print, fullscreen, etc) that the TemplateMain will need to listen to in order to run the relevant functions. At the moment, the Template listens for the click mouseevent and then uses a switch statement to get the initial target of the event, eg:
protected function onTitleBarClick(e:MouseEvent):void {
switch (e.target){
case (titleBar.settingsButton):
addSettings();
break;
// etc..
}
}
Would there be any advantage or is it desirable to port this into a custom event system, either extending the native Event class or maybe even as3signals so that the titlebar itself has the click listener and then dispatches an event that TemplateMain picks up and then acts accordingly? One negative of this I can see is that, along with mouse click listener, I’d end up with another six listeners for the custom events.
Like I said, maybe it doesn’t matter but I’d like to know how others handle this very common situation.
I personally prefer to stay as close as possible to the “black box” principle where one component needs to know as little as possible from another component.
I would go for defining the events in the TitleBar. When the TemplateMain receives an event , it doesn’t have to know where the event comes from , just what it is and how to react to it.
This gives you a couple of options, you can use a dispatcher object , or the TitleBar itself can be the dispatcher, although I always prefer when components are loosely coupled.
On the event listening end, to use a single handler or many functions would depend on the content of your functions really. i would go for clarity & legibility. I don’t see the point of creating a function for a one liner, in such case I would favor the switch statement.
As for creating a number of listeners, I don’t see this as a problem , it allows you to easily remove one or the other depending on the function’s life.