Game Development Reference
In-Depth Information
Here's a quick-start guide to dispatching events:
1. Import the Arajp class:
2. When something happens that any objects in your game might be interested in, create an
event for it using the `eol]p_dArajp method. The basic format for creating an event looks like
This directive broadcasts to the rest of your program that an event has occurred. You can give
the event any name you like, such as arajpJ]ia, as in this example.
3. Any other class can now listen to this event by adding an event listener, like this:
In your games, you'll probably want to add the event listener to the op]ca for reasons I'll
explain ahead. You can attach event listeners to any object, however.
4. You then need to create the event handler to make something happen when the event occurs:
In the event handler, you can use the event object's p]ncap to access the object that called the
event and all its properties. If you want to access the object with which the event was regis-
tered, such as the op]ca in this example, use the _qnnajpP]ncap property.
5. Wait for the event to occur.
You can create events for anything in your game that you think other objects should know about, such
as a door opening, an enemy being destroyed, or a variable changing its value. Any objects can then
choose to listen to those events if they want to, and take actions based on them.
By using events, objects can communicate without having to use setters (and sometimes even getters)
in most cases. You can create classes that are completely encapsulated and don't depend on other
classes to function properly. They can listen for events that interest them and change their own private
properties internally.
Let's take a closer look at how dispatching events works.
Event “bubbling”
When events are dispatched, they travel through three different states: capture , target , and bub-
bling . The state that I'll explain in detail is the bubbling state, which is most useful in the kinds of
game design scenarios that you've seen at work in this topic.
When an object dispatches an event, the object broadcasts the event like a radio station broadcasts
a news item. Other objects can then “tune in” to the event if they want to listen to it.
Search Nedrilad ::

Custom Search