【求助】quick-cocos中 handler的问题

下边是新建的例子小游戏中GameView.lua文件中关于handler使用的一个例子,可是一直不明白step的参数dt怎么赋值进去的:

请大哥们指导解释下。谢谢~

function GameView:start()
    self:scheduleUpdate(handler(self, self.step))
    return self
end

function GameView:step(dt)
    if self.lives_ <= 0 then return end

    self.addBugInterval_ = self.addBugInterval_ - dt
    if self.addBugInterval_ <= 0 then
        self.addBugInterval_ = math.random(GameView.ADD_BUG_INTERVAL_MIN, GameView.ADD_BUG_INTERVAL_MAX)
        self:addBug()
    end

    for _, bug in pairs(self.bugs_) do
        bug:step(dt)
        if bug:getModel():getDist() <= 0 then
            self:bugEnterHole(bug)
        end
    end

    return self
end


```

其实你看看 scheduleUpdate 的源码就明白了。这个是调用 cocos node的 update 方法。GameView:step(dt) 是注册在 c++的,然后被 每帧回调回来。

嗯,好滴。不过我是初学这个,源码目录是什么,找这个handler的实现一直没找到。。
上边那个问题和这个差不多,不过这个函数所需要的就是event事件,是不是都是在c++的实现里指定传入什么值的么?

  -- add touch layer
    display.newLayer()
        :onTouch(handler(self, self.onTouch))
        :addTo(self)


function GameView:onTouch(event)
    if event.name ~= "began" then return end
    local x, y = event.x, event.y
    for _, bug in pairs(self.bugs_) do
        if bug:getModel():checkTouch(x, y) then
            self:bugDead(bug)
        end
    end
end


```

嗯,好滴。不过我是初学这个,源码目录是什么,找这个handler的实现一直没找到。。
上边那个问题和这个差不多,不过这个函数所需要的就是event事件,是不是都是在c++的实现里指定传入什么值的么?

– add touch layer
display.newLayer()
:onTouch(handler(self, self.onTouch))
:addTo(self)

function GameView:onTouch(event)
if event.name ~= “began” then return end
local x, y = event.x, event.y
for , bug in pairs(self.bugs) do
if bug:getModel():checkTouch(x, y) then
self:bugDead(bug)
end
end
end

建议你用sublime查function handler就知道handler在哪了
对于第二个问题,你得先明白quick只是对cocos2d-x的再一次封装

多谢大哥。handler的lua函数体倒是找到了,不过用c++怎么实现的,这个没找到,你说的是用sublime来找handler的c++实现么?

handler是纯lua实现啊,没有C++代码的,通过传递self参数,用它可以方便将类方法当作回调函数

嗯,你说的是这个吧。

function handler(obj, method)
returnfunction(…)
return method(obj,…)
end
end

现在的问题是,我前边楼上贴出的代码:
handler(self, self.step)
或者handler(self, self.onTouch)

这样的话,handler其实是把step方法和onTouch方法封装了再返回,不过step和onTouch方法都带有参数,需要分别给参数dt 和event,
可是在我贴出的代码中并没有见handler给step和onTouch传入参数,但是方法里dt和event是有值的。
而dt和event两个参数,之前我也没有定义过。
所以不明白这两个参数dt和event是cocos里定义好的全局变量么?
谢谢!~

那个肯定不是全局变量吧,这样设计就恶心了,那个是在调用注册的回调函数时传进去的参数

嗯嗯,不过如果不是有设置好dt是什么的话,如果要传入dt给self:step(dt)方法,那么不是应该这么写嘛:handler(self, self.step)(dt),这样来传入。对不对?
可是我在cocos建立的那个例子里看到,直接这么写handler(self, self.step),没传入dt,就已经可以了。所以不一直搞不明白啊。。。求大哥指点。谢谢:6:

不对,说了它是注册的回调函数啊!就是这个函数是在其它地方调用的(C++代码中),你先把回调函数弄明白吧
cocos中下面那个_callback就是你注册到scheduler中的回调函数(handler(self, self.step)),然后调用通过_callback(_elapsed);将参数传递进去了,
_elapsed就是dt的值,所以你在lua中直接用就可以了
void TimerTargetCallback::trigger()
{
if (_callback)
{
_callback(_elapsed);
}
}

想要了解这个问题 请搜索 lua handler 匿名函数

我也是初学,看你的评论顿时就明白了,谢谢大神