Dispatching Events Problem

Very simple code but I can’t get eventHandler function to fire, could this be a bug?

display.setDefault( "background", 1, 1, 1 )

local bg = display.newRect(0, 0, 100, 100)
bg:setFillColor(1, 1, 0);

function eventHandler(event)
    print("Event was raised")
end


bg:addEventListener("myEvent", eventHandler)


Runtime:dispatchEvent({ name = "myEvent", target = {} })

Is there a reason you’re not more closely following the syntax laid out in the docs?

You’ve added the event listener to bg, but you’re trying to dispatch the event to Runtime.

I assumed that Runtime was a global dispatcher where any object listening to a ( “custom” ) event would hear the event coming from Runtime. ex - obj:addEventListener(“touch”, eventHandler)

I even tried to asking ChatGPT about the issue and this was the response

local function eventHandler(event)
    print("Event was raised")
end

local bg = display.newRect(0, 0, 100, 100)
bg:addEventListener("myEvent", eventHandler)

bg:dispatchEvent({ name = "myEvent", target = bg })

1 Like

ChatGPT’s answer is in line with what I said.

If you add an event listener to an object, then you can dispatch those events to said object. If you add event listeners to Runtime, then you can dispatch said events there.

Runtime is a global variable, but it’s just one table, like Solar2D display objects.

Thank you for the clarification, it was a misunderstanding from my part.