cocos游戏开发中,创建一个全局的事件监听和派发类来管理全局的事件监听和注销等操作

144 阅读1分钟

在cocos游戏开发中,node自带的on和off事件只能在自己对象内部实现事件注册和派发,但是如果想实现全局的事件注册和派发,比如:一架飞机击杀了多少敌机,就将这个数量显示在ui组件上,这个时候,就需要给飞机注册一个事件,然后在ui组件上绑定这个事件,当飞机击杀了敌机后就触发这个事件,ui组件就会更新数量。

事件脚本

创建一个事件脚本,内容如下:

import { _decorator, Component, Node } from 'cc'
const { ccclass, property } = _decorator

interface EventData {
    func: Function
    target: any
}

interface EventList {
    [eventName: string]: EventData[]
}

@ccclass('eventMan')
export class eventMan extends Component {
    // 全局事件注册和监听
    // 添加属性用于存储事件名称和事件的映射关系
    public static handler: EventList = {}

    // 绑定事件
    public static on(eventName: string, callback: Function, target: any) {
        if (!this.handler[eventName]) {
            this.handler[eventName] = []
        }
        this.handler[eventName].push({
            func: callback,
            target: target,
        })
    }

    // 取消监听
    public static off(eventName: string, callback: Function, target: any) {
        if (!this.handler[eventName]) {
            return
        }
        const eventList = this.handler[eventName]
        for (let i = 0; i < eventList.length; i++) {
            const event = eventList[i]
            if (event.func === callback && event.target === target) {
                eventList.splice(i, 1)
                break
            }
        }
    }

    // 事件派发
    public static dispatch(eventName: string, ...args: any[]) {
        if (!this.handler[eventName]) {
            return
        }
        const eventList = this.handler[eventName]
        for (let i = 0; i < eventList.length; i++) {
            const event = eventList[i]
            event.func.apply(event.target, args)
        }
    }

    // 事件监听和派发机制
    start() {}

    update(deltaTime: number) {}
}

可以配置一些全局的事件:

export enum EventName {
    STARTSHA = 'STARTSHA',
    ENDSHA = 'ENDSHA',
    SHOWICON = 'SHOWICON',
    HIDEICON = 'HIDEICON',
}

使用步骤

使用的时候,引入这个组件,然后注册事件和回调函数:

触发事件的地方: