cocos2d-lua 3.x版本的通知EventListenerCustom dispatchEvent


function CustomEventTest:onEnter()
    local origin = cc.Director:getInstance():getVisibleOrigin()
    local size = cc.Director:getInstance():getVisibleSize()
    local count1 = 0
    local count2 = 0
    
    cc.MenuItemFont:setFontSize(20)

    local statusLabel1 = cc.Label:createWithSystemFont("No custom event 1 received!", "", 20)
    statusLabel1:setAnchorPoint(cc.p(0.5, 0.5))
    statusLabel1:setPosition(cc.p(origin.x + size.width/2, origin.y + size.height-90 ))
    self:addChild(statusLabel1)

    local function eventCustomListener1(event)
        local str = "Custom event 1 received, "..event._usedata.." times"
        statusLabel1:setString(str)
    end

    local listener1 = cc.EventListenerCustom:create("game_custom_event1",eventCustomListener1)
    self._listener1 = listener1
    local eventDispatcher = self:getEventDispatcher()
    eventDispatcher:addEventListenerWithFixedPriority(listener1, 1)

    local function sendCallback1(tag, sender)
        count1 = count1 + 1
        
        local event = cc.EventCustom:new("game_custom_event1")
        event._usedata = string.format("%d",count1)
        eventDispatcher:dispatchEvent(event)
    end
    local sendItem1 = cc.MenuItemFont:create("Send Custom Event 1")
    sendItem1:registerScriptTapHandler(sendCallback1)
    sendItem1:setPosition(cc.p(origin.x + size.width/2, origin.y + size.height/2))

    local statusLabel2 = cc.Label:createWithSystemFont("No custom event 2 received!", "", 20)
    statusLabel2:setAnchorPoint(cc.p(0.5, 0.5))
    statusLabel2:setPosition(cc.p(origin.x + size.width/2, origin.y + size.height-120 ))
    self:addChild(statusLabel2)

    local function eventCustomListener2(event)
        local str = "Custom event 2 received, "..event._usedata.." times"
        statusLabel2:setString(str)
    end

    local listener2 = cc.EventListenerCustom:create("game_custom_event2",eventCustomListener2)
    CustomEventTest._listener2 = listener2
    eventDispatcher:addEventListenerWithFixedPriority(listener2, 1)

    local function sendCallback2(tag, sender)
        count2 = count2 + 1
        
        local event = cc.EventCustom:new("game_custom_event2")
        event._usedata = string.format("%d",count2)
        eventDispatcher:dispatchEvent(event)
    end
    local sendItem2 = cc.MenuItemFont:create("Send Custom Event 2")
    sendItem2:registerScriptTapHandler(sendCallback2)
    sendItem2:setPosition(cc.p(origin.x + size.width/2, origin.y + size.height/2 - 40))

    local menu = cc.Menu:create(sendItem1, sendItem2)
    menu:setPosition(cc.p(0, 0))
    menu:setAnchorPoint(cc.p(0, 0))
    self:addChild(menu, -1)
end

你可能感兴趣的:(cocos2d-lua 3.x版本的通知EventListenerCustom dispatchEvent)