Laya游戏开发实战

Laya Handler

2019-11-24  本文已影响0人  s0ok

不管是开发游戏还是其他应用或者Web,经常会使用到异步方法,使用异步函数的时候需要有回调函数。
比如JS中回调函数的使用

        var callFunc = function(){
            console.log('我是回调函数')
        }
        setTimeout(callFunc, 1000);

Laya中将回调函数封装在Handler中。并通过对象池统一管理。

Handler(事件处理器)

Handler是Laya中的事件处理类,在Laya中加载资源回调,动画播放回调等都是通过Handler。



Handler类的API也很简单,4个属性,6个方法。

Properties

Methods

示例代码

                // 一定不要 new Handler,通过create创建Hander
        const handler = Laya.Handler.create(this,()=>{
            console.log("无参的回调函数")
        });
        handler.run();

create方法源码

    Handler.create=function(caller,method,args,once){
        (once===void 0)&& (once=true);
        if (Handler._pool.length)return Handler._pool.pop().setTo(caller,method,args,once);
        return new Handler(caller,method,args,once);
    }

可以看到创建时首先判断对象池是否为空,为空时才会new Handler。如果我们通过new Handler的方式创建对象池会一直增加,可能造成内存溢出。

        handler.setTo(this,(param_0,param_1)=>{
            console.log('参数:' + param_0);
            console.log('参数2:' + param_1);
        },['第一个参数','第二个参数'],false);

        handler.run();
/**
    *执行处理器,并携带额外数据。
    *@param data 附加的回调数据,可以是单数据或者Array(作为多参)。
    */
    __proto.runWith=function(data){
        if (this.method==null)return null;
        var id=this._id;
        if (data==null)
            var result=this.method.apply(this.caller,this.args);
        else if (!this.args && !data.unshift)result=this.method.call(this.caller,data);
                // 如果回到方法带参且通过runWith执行,则将两组参数拼接
        else if (this.args)result=this.method.apply(this.caller,this.args.concat(data));
        else result=this.method.apply(this.caller,data);  
                // 执行结束后将handler对象放回对象池
        this._id===id && this.once && this.recover();
        return result;
    }
        handler.setTo(this,(param_0,param_1,param_2)=>{
            console.log('参数:' + param_0);
            console.log('参数2:' + param_1);
            console.log('参数3:' + param_2);
        },['第一个参数','第二个参数'],false);

        //handler.run();
        handler.runWith('第三个参数');
上一篇 下一篇

猜你喜欢

热点阅读