如何在 Corona 中允许本地事件监听器方法
假设我在一个类中有一个事件监听器,如下所示:
Vehicle = {}
...
function Vehicle:touch(event)
-- do something with self
return
end
displayObject:addEventListener("touch", self)
如何将“touch”方法设置为本地方法,以便没有人有从该类之外调用它的冲动?不会让编译器抱怨。
谢谢迈克。我没有意识到你可以像 UI.lua 那样做:
local function newButtonHandler( self, event )
...
end
function newButton( params )
...
button.touch = newButtonHandler
button:addEventListener( "touch", button )
...
end
但是,其中的参数(self,event)
local function newButtonHandler( self, event )
是我以前从未见过的东西 - 通常只是(事件)。 self 以及事件是否作为 addEventListener 的暗示自动发送到事件侦听器方法?
不管怎样,我最初想要做的是有一个与显示对象不同的对象(称之为“buttonManager”)被发送到类 eventListener 方法,因为我需要在那里访问buttonManager。所以我想我可以写:
button:addEventListener( "touch", buttonManager )
但这会导致 eventListener 根本没有被调用。如何将 ButtonManager 获取到 eventListener?
Say I have an eventlistener in a class as follows:
Vehicle = {}
...
function Vehicle:touch(event)
-- do something with self
return
end
displayObject:addEventListener("touch", self)
How do I make the "touch" method local so that nobody gets the urge to call it from outside this class? Without making the compiler complain.
Thanks Mike. I didn't realize you could do as UI.lua does:
local function newButtonHandler( self, event )
...
end
function newButton( params )
...
button.touch = newButtonHandler
button:addEventListener( "touch", button )
...
end
However, the parameters (self, event) in
local function newButtonHandler( self, event )
is something I haven't seen before - ususally only (event). Does self, as well as event get sent along to the event listener method automagically as an implication of addEventListener?
Anyway, what I originally wanted to do is to have a different object (call it "buttonManager") than the display object be sent along to the class eventListener method, because I need access to buttonManager there. So I thought I could write:
button:addEventListener( "touch", buttonManager )
But that results in the eventListener not being called at all. How do I get buttonManager to the eventListener?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在我看来,您可以为您正在设计的类创建一个单独的模块,并使触摸处理程序成为该模块的本地函数。请参阅 Corona 的 ui.lua 文件(包含在他们的许多示例项目中)以了解他们是如何做到这一点的。
这是从他们的代码中总结出来的。可以看到,newButtonHandler是本地的,所以不能被外界调用。
希望有帮助!
It sounds to me like you could create a separate module for the class you're designing, and make the touch handler a local function to that module. See Corona's
ui.lua
file (included in many of their sample projects) to see how they do it.This is boiled down from their code. As you can see, newButtonHandler is local, so it cannot be called by the outside world.
Hope that helps!