typescript侦听事件

本文介绍Laya引擎中的事件分发机制实现原理及使用方法。详细解释了如何通过Dispatcher类注册事件监听器、取消监听及触发事件,并提供了具体的接口定义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Laya.EventDispatcher是表示Laya引擎中API,需要创建一个父类接口,通过父类接口指向子类对象,当调用接口方法时,
会自动调用其子类重写方法

export interface IEventDispatcher {
on(type: string, caller: any, listener: Function, args: Array<any>): Laya.EventDispatcher;

once(type: string, caller: any, listener: Function, args: Array<any>): Laya.EventDispatcher;

off(type: string, caller: any, listener: Function, onceOnly: boolean): Laya.EventDispatcher;

offAll(type: string): Laya.EventDispatcher;

event(type: string, data: any): boolean;

hasListener(type: string): boolean;
}

import { IEventDispatcher } from "./IEventDispatcher";


export class Dispatcher {
    private static _dspt: IEventDispatcher = new Laya.EventDispatcher();
    constructor() {}
 
    /**
     * 侦听事件
     * @param type 事件的类型
     * @param caller 事件侦听函数的执行域(一般为this)
     * @param listener 事件侦听函数
     * @param args (可选)事件侦听函数的回调参数
     */
    public static on(type: string, caller: any, listener: Function, args: any[] = null): void {
        Dispatcher._dspt.on(type, caller, listener, args);
    }
     
    /**
     * 移除侦听
     * @param type
     * @param caller
     * @param listener
     * @param onceOnly
     */
    public static off(type: string, caller: any, listener: Function, onceOnly: boolean = false): void {
        Dispatcher._dspt.off(type, caller, listener, onceOnly);
    }

    /**
     * 派发事件。
     * @param type  事件类型。
     * @param data  (可选)回调数据。<b>注意:</b>如果是需要传递多个参数 p1,p2,p3,...可以使用数组结构如:
      [p1,p2,p3,...] ;如果需要回调单个参数 p ,且 p 是一个数组,则需要使用结构如:[p],其他的单个参数 p ,可以直接传入参数 p。
     * @return 此事件类型是否有侦听者,如果有侦听者则值为 true,否则值为 false。
     */
    public static event(type: string, data?: any): void {
        Dispatcher._dspt.event(type, data);
    }

    public static hasListener(type: string): boolean {
        return Dispatcher._dspt.hasListener(type);
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值