Game Development Reference
In-Depth Information
Additional data can also be added to the events and passed to the handler. Here's an example:
local myEvent = Event.new("myEvent")
myEvent.data1 = "Data One"
myEvent.data2 = "Data Two"
function theFunc(param)
print("Invoked with \n\t" .. param.data1 .. ", " .. param.data2)
stage:removeEventListener("myEvent", theFunc)
end
function raiseEvent(msg)
print(msg)
myEvent.data1 = msg
stage:dispatchEvent(myEvent)
end
stage:addEventListener("myEvent", theFunc)
-- Invoke the event
print("------------\nInvoking the event")
Timer.delayedCall(1000, raiseEvent, "first time")
Timer.delayedCall(5000, raiseEvent, "second time")
Timer.delayedCall(10000, raiseEvent, "third time")
When the program is run, the timer initially fires at 1,000 ms, and this calls the raiseEvent handler.
The program then prints the message “first time,” and that in turn dispatches the custom event.
When the custom event is fired, it prints the data1 and data2 members of the parameter passed to
the handler, and finally the event handler is removed.
After 5,000 ms, the raiseEvent function is called again, the message “second time” is printed, the
custom event is dispatched. However, because we removed the event listener the last time, the
theFunc function is not called.
After 10,000 ms, the message “third time” is printed, and since the event listener is no longer in
effect, nothing happens.
Now you know how to set up an event listener, dispatch custom events, and also remove event
listeners.
Querying Events
If you have set an event listener or would like to know if a particular event listener is set on an object,
then you can use the function hasEventListener .
print(stage:hasEventListener("noEvent"))
 
Search WWH ::




Custom Search