ActionScript - Should Event Dispatching/Listening Be Avoided Where Possible? - actionscript-3

recently, i ran into a problem where i needed to access the List object from the List's custom cell renderer class.
there were 2 options:
listen for and dispatch a custom event to communicate between the 2 classes.
reference the List from the cell renderer class with the parent property: List(parent.parent.parent)
while it's much easier to choose the second option, i feel that dispatching and listening for a custom event would result in code that's more inline with the design of AVM2, offers greater control for communication and, as it's expected AS3, should be less difficult to debug or maintain within new hands.
however, i also feel that using an event is more expensive, requires attention to resource management perhaps making it more difficult to debug and maintain and could be generally overkill.
is this simply a matter of needs or taste? should dispatching/listening for custom events be avoided if they can be?

Don't forget that you can't see the control flow of event listeners from single glances at the code.
While I'm not against event listeners completely, if you use them, you should try to use them in the most self-documenting and simple way possible. If you have clever stuff, like adding/removing event listeners, and it goes wrong, then it can be a nightmare to debug because you cannot see what dispatchEvent is going to do.
If owner gets you the right object, then I would just go with that, myself.

I would look at it from another angle. If the other option ends up creating more dependency between the two classes, I would definitely opt for event dispatching.
In that regard , I'm not sure why you think that an event driven application would be harder to debug & maintain. It would seem to be the opposite, but it would of course depends on how one implements the event dispatching in the application. But saying this and re-reading your question I realize you seem to contradict yourself! Of course , I tend to agree with the first statement.
...offers greater control for communication and, as it's expected AS3,
should be less difficult to debug or maintain...
...perhaps making it more difficult to debug and maintain and
could be generally overkill.

Related

What is the purpose of hasEventListener and willTrigger in IEventDispatcher?

I'm implementing the observer pattern for a project in a similar way as AS3 does it, i.e. with the IEventDispatcher interface. The reason is because I'm quite fond of it. I know it has received some critisism, but I like it.
However I'm a bit of a perfectionist so I would like to slim it down if possible. The IEventDispatcher interface has the methods hasEventListener and willTrigger and I don't really understand what those methods are good for. I understand, as the documentation say, that they are for checking if there are any listeners registered for a particular event. But... when would one actualy want to check that? Does anyone have a use case where those methods are indispensable?
I believe internally there were some calls to dispatchEvent that would first check if any listeners were present before dispatching the event. I recall this being an issue where if certain listeners weren't registered other code didn't execute, though I can't recall the exact case right now.
One good way to figure this out would be to grep the Flex source and see how they are used there.
Edit
Just did a grep for hasEventListener on Flex source 4.9.1 and it comes up in 151 files. Lots of places it appears to just check if any event listeners are registered for some event type before it dispatches the event (to avoid unnecessary event creation and dispatch calls I would guess). In searching for willTrigger I find it used for similar situations.

Game programming without a main loop

My professor gave my class an assignment today based on object oriented programming in Pygame. Basically he has said that the game that we are to create will be void of a main game loop. While I believe that it is possible to do this (and this question has stated that it is possible) I don't believe that this is required for adherence to the Object Oriented paradigm.
In a diagram that the professor gave, he showed the game initializing and as the objects were instantiated the control flow of the program would be distributed among the objects.
Basically I believe it would be possible to implement a game this way, but it would not be an ideal way nor is it required for Object Oriented adherence. Any thoughts?
EDIT: We are creating an asteroids clone, which I believe further complicates things due to the fact that it is a real time action game.
Turn based games or anything event driven would be the route to go. In other words, take desktop GUI apps. They'll just tick (wait) over until an event is fired. The same could be done for a simple game. Take Checkers for example. Looping each game cycle would be overkill. 90% of the time the game will be static. Using some form of events (the observer design pattern would be nice here) would provide a much better solution. You're using Pygame, so there may be support for this built in, through due to my limited use I cannot comment fully. Either way, the general principles are the same.
All in all it's a pretty rubbish assignment if you ask me. If it's to teach you event driven programming, a simple GUI application would be better. Even the simplest of games us a basic game loop, which can adhere to OO principles.
Hmm. In the general case, I think this idea is probably hokum. SDL (upon which PyGame is implemented), provides information to the program via an event queue, and consuming that queue requires some sort of repeatedly checking the queue for events, processing them, and waiting until the next event arrives.
There are some particular exceptions to this, though. You can poll the mouse and keyboard for their state without accessing the event queue. The problem with that is it still requires something like a loop, so that it happens over and over again until the game exits.
You could use pygame.time to wait on a timer instead of waiting on the event queue, and then pass control to the game objects which poll the mouse and keyboard as per above, but you are still 'looping', but bound by a timer instead of the event queue.
Instead of focusing on eliminating a main loop, how about instead think about using it in an object oriented way.
For instance, you could require a 'root' object, which actually has its own event loop, but instead of performing any action based on the incoming events, it calls a handler on several child objects. For instance when the root object recieves a pygame.event.MOUSEBUTTONDOWN event, it could search through it's children for a 'rect' attribute and determine if the event.pos attribute is inside that rect. if it is it can call a hypothetical onClick method on that child object.
I think it might qualify as event driven programming? Which can still be object oriented. You see this in Flash a lot.
There's a difference between a main loop in a main class. You can still have a game class initialize all of your objects, and then rely on inputs to move the game onward.
Kinda hard to say exactly without knowing the exact parameters of your assignment, the devil is in the details.
You might look at how python utilizes signals. A decent example I found is at: http://docs.python.org/library/signal.html

What are some good use cases for the CALLBACK pattern/idiom?

I don't use this pattern, maybe there are some places where it would have been appropriate and I used something else. Have you used it in your daily coding? Feel free to give samples, in your language of choice, along with your explanation.
Callbacks aren't really a "pattern" - more like a building block. A number of the gang of four design patterns use virtual methods in a callback-like way. Justin Niessner has already mentioned Observer.
Callbacks are much older than OOP (and probably older than 3GLs and even assembler). Another old idea is the parameter block - the C interpretation being a struct full of related members to be passed to a function so that function doesn't need a huge parameter list.
OOP classes build upon the parameter block (and add a philosophy to it). The class instance itself is a parameter block passed by reference to its methods. The virtual table is a dispatch-handling parameter block. Every virtual method has a callback pointer in the dispatch-handling parameter block. A pure virtual method reserves space for the callback pointer in the parameter block, and promises to provide the actual pointer later.
Since the class is the building block for object oriented design patterns, and parameter blocks and callbacks are the building blocks of classes - well, you could claim that all OOP design patterns are built from these ideas.
I'd like to be able to say "parameter blocks and callbacks, plus style rules guiding their use, inspired object orientation" but as appealing as it sounds, I don't know whether it's true.
I use callbacks pretty much every day in the following scenarios:
Events: When the user clicks their mouse on a control, presses a key or otherwise interacts with the UI in a way I need to handle, I subscribe to the delegate that the control publishes for the event. I can then handle it by updating the UI, cancelling the event in certain circumstances or otherwise taking some special action.
Multithreaded Programming: When programming a GUI, it's important to keep the UI responsive and indicate the progress of a long-running background event to the user. To do this, I kick off the task in a separate thread and then publish delegates (events in the .NET world) that provide my UI with the opporutinty to notify the user about progress that's happening.
Lambda functions: In .NET, lambda functions are a form of a delegate, one that lets me interact with another piece of code's operation at a later point in time. LINQ is a great example of this. I can create a small matching function and then supply it to a LINQ query. Later, when I execute my query against a collection, the matching function is called to determine if there is a match for the query. This allows me to not have to build or worry about the query mechanism. I just have to tell the query mechanism where to go to find out if a comparison is a match or not.
These examples just scratch the surface, I'm sure. But they are useful examples of how I use callbacks every day.
The .NET platform uses callbacks heavily to implement the Observer pattern.
They also get used for handling Asynchronous processes.
Objective C and the Cocoa framework make a lot of use of it. An example would be NSURLConnection, which will inform an object given to it (called its delegate) when something happens on the connection:
NSURLConnection *foo = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Note the passing of delegate there. The request proceeds in the background, and the instance will then send messages to the delegate (in this case, self), like:
connectionDidFinishLoading:
connection:didFailWithError:
You get the idea. I believe this is called the "observer pattern". It's all tied in to Cocoa's event loop (as far as I know, I'm still learning) and is cheap 'n easy asynchronous programming. A lot of frameworks in a variety of languages follow this approach.
.NET has delegates as well, which are similar. Think events.
I use it a great deal in javascript to let me know when an asynchronous call has finished, so the result can be processed.
But, in javascript, and now in C#3, I pass in functions as a parameter, so that the processing can go on without explicitly setting up a delegate to be called.

AS3: Model and View Communication in a Game

So I'm attempting to use the MVC pattern for a game I'm working on. Everything has been going pretty smoothly so far, but I'm having trouble figuring out how to get my model and my view to talk to each other effectively.
My general model structure involves lots of nested information.
a Level has Rooms
a Room have Layers
a Layer has Objects
Each layer has an index and a corresponding layer in the view that is rendering it. I need the objects to post an update message as they animate so it's corresponding layer in the view can update. I'm trying to use the built in event system to handle these updates.
My issue is I'm not sure how to avoid putting listeners on every object in the game - which strikes me as bad ( perhaps I'm wrong here ). If I change the rooms, the layer doesn't have a way of removing listeners from the objects in the last room because it only accesses layers through the current room. Objects are only updated when they are in the current room, so the other objects won't need to fire events.
The view is set up to cascade events to all of the children, so the root node can receive all updates ( I think I did that part correctly ), and the layer can match the target because it knows which layer it's rendering. The problem is getting the message out from the objects to the view.
Of course this makes sense to me, because I've been working with the code for a while now.
If I can provide more clarification please ask. This is my first time working with the MVC pattern, so I'm sure I could do things better.
If you have any suggestions as to how I might solve this conundrum, please share!
Edit: I have something working keeping track of the current layerset from outside of the view and the model which manages adding/removing the appropriate event listeners and delegating the update event to the layer as suggested. But please, anything I can do to improve this please do.
If you are new to MVC you may want to check out the PureMVC framework for AS3. When I first started learning MVC I started by trying to build my own implementation of the pattern. After trying out PureMVC I got a much better understanding of the structure of MVC.
Your rooms/layers/objects sound like they have a parent/child like relationship and may be a good candidate for the composite design pattern. Basically this is a tree like structure where you could trigger an event which would then cascade through all branches. If you do a search for 'composite pattern' you may get a better explanation of how this may work for you.
There a few solutions you could take, adding event listeners is reasonable, but as mentioned you are going to need to make sure you clean them up appropriately, but this will be a requirement with a lot of other solutions as well.
Another one would be to pass in the layer on object construction, perhaps in the form of a "parent" property. In this case the object would notify its parent whenever it has changed, then on layer update, it would go through and handle all objects who have registered as having changed. This has performance benefits in that the object could change several time between renders, but the parent would only act on this changes once, (when its been told to update itself.) In this case you would still need to make sure you clean up your references properly to avoid garbage collection problems.
Yet another solution would be objects register with them selves as having been changed, typically in the form of a simple Boolean value. In this case the parent (your layer) would loop through all children, presumable stored in some form of collection, and handle updates to all those who say they've been changed. This solution removes the dependencies from object to layer, but in extreme cases, could lead to performance issues, (Extreme case being so many objects the process of checking a single Boolean value on them is too much to handle (that'll be A LOT of objects))
Hope that helps.
Using the Mediator pattern in PureMVC, rather than putting listeners on every object, you could have a Mediator listen to the application instance for the events. Then inside the actual objects, send a bubbling event that bubbles up the display hierarchy to the application where the Mediator hears it. Then the mediator takes the appropriate action such as sending off a notification to trigger a command with some logic, perhaps. The target of the event, would of course be the item in your world that sent the event, so if the Command would need to manipulate or inspect that item, then just pass the event.target in the notification body. QED.
-=Cliff>

AS3: Faster to use EventListeners or ArrayLoops?

I am writing a game in AS3 and have, as an example, around 40 objects on screen. Let's say they are clouds. I'm wondering which of the two paths would be less a strain on system resources:
a) Put an eventListener on each object and have it update itself, or
b) Loop through the array and manually update each object
Or is the performance difference negligable? Does either solution scale better than the others?
I would expect the performance to be fairly negligable either way. Once you get a lot of objects you might see a difference (with the loop being the winner). From my experience Adobe put a lot of work into optimizing the actionscript event listener path.
This is a tricky one, purists would say to to go with the array looping method, as with this method it would be possible to cut out the 'view' out of the MVC and still have the system working (which is a good test of any system). However, if you are working with the events you can cut some corners with event bubbling and strict typing.
For example if we assume you make a custom event called CloudEvent that has a property called cloud that contains a reference to the dispatching CloudSprite, then as long as the event bubbles by default, you don't need to add an event listener to each one, just to the DisplayObjectContainer which holds them (which I am imaginatively calling CloudContainer). This way the event bubbles up and you only have to add one listener, and don't have to worry about managing listeners on child items.
public function CloudContainer()
{
super();
addEventListener(CloudEvent.CHANGE, cloudChangeHandler);
}
private function cloudChangeHandler(evt:CloudEvent):void
{
var cloud:CloudSprite = evt.cloud;
cloud.update();
}
Hope this helps
I am under the impression that event listeners require more resources so it is better to use an array when performance is required. It would also scale better for that reason. If you are using Flash 10 then use a Vector, I believe it offers better performance than an array (and type saftey).
Use EventListeners! Just make sure you manage them properly ie. remove them when you done, use weak references.
You wont really find much performance from doing things like this. Usually better performance comes from the bigger ticked items, like not using filters, lowering the frame-rate etc. So punishing your code clarity and OO for the sake of a half a millisecond is not worth it in my book.
There are a few really great guides out there that will teach you all about optimizing in AS3. The best one I have found is Grant Skinner's; AS3 Resource Management. And I just found a quicker seven step version. I would definitely recommend everyone doing AS3 should read the Grant Skinner slides though.
Of course don't just take my word (or anyone else answering your question), you can do you own tests and actually see whats up using a profiler. See Lee Brimlow's latest video tutorial for how to do this. It is worth the watch! Check it out here: GotoAndLearn - ActionScript 3 Performance Testing.