dispatchEvent?

Hi all,

In AS3, I can instantiate an object "foo" from Foo.as in my main.as and set up an event listener "bar" in main, then have my "foo" object dispatchEvent("bar"). main.as and any other class set up to listen to that event would then handle it.

How would I do that in Lua/Corona? For example, if I want the player to broadcast their coordinates, and then have any object listening for that to act accordingly.

I've looked in many of the Flash to Corona discussions and the Lua documentation, and haven't been able to grasp custom event dispatches yet, only the built-in system ones.

This should be what you're looking for.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
-- Listener function that will receive events
local onCreation = function( event )
 
     print( event.x, event.y )
 
end
 
-- Register a custom event, in this case "objectCreated"
Runtime:addEventListener( "objectCreated", onCreation )
 
-- Create an object
local image = display.newImage( "image.png" )
 
-- Fire the event
Runtime:dispatchEvent{ name = "objectCreated", x = image.x, y = image.y }

Thanks for the custom event information Graham. Is it possible to do something like this? Do events only exist within their own scope?

main.lua

1
2
3
4
instantiate player object
instantiate enemy object
addeventlistener("foo", bar)
function bar() print("main bar") end

You have some syntax issues there but yes different modules can listen for events fired from other modules.

That was pseudocode, but yes there are syntactical issues in my code.. I can't seem to get either main or enemy to handle the event. From the dispatching module, does Runtime:dispatchEvent(event) broadcast globally? Here's what I have:

main.lua:

1
2
3
4
5
6
7
8
9
player = require("player")
 
player:foo()
 
function bar()
print("bar")
end
 
Runtime:addEventListener("bar", bar)

The problem is in the order of your events, you are firing the event before registering a handler.
Try this:

main.lua

1
2
3
4
5
6
7
8
9
10
player = require("player")
 
function bar()
       print("bar")
end
 
Runtime:addEventListener("bar", bar)
 
player:foo()
 

Well, there you go. Thanks!

No worries, it's always the little things :-)

views:1838 update:2011/10/10 15:46:04
corona forums © 2003-2011