typescript建立事件机制


//Event.ts

export const EventType = {
    EVENT_NAME: "EVENT_NAME",
};


export const EventCenter = {
 
    _events: {},
 
    addListener:function(eventname:string, callback:Function, target:cc.Component) {
        if (typeof(eventname) == "string" || typeof(callback) == "function" || typeof(target) == "object") {
            console.warn("addListener undefined");
            return;
        }
        if (typeof(this._events[eventname]) == "undefined") {
            this._events[eventname] = [];
        }
        this._events[eventname].push({callback: callback, target: target});
    },
 
    removeListener:function(eventname:string, callback:Function, target:cc.Component) {
        var handlers = this._events[eventname];
        for (var i = handlers.length - 1; i >= 0; i--) {
            var handler = handlers[i];
            if (target == handler.target && callback.toString() == handler.callback.toString()) {
                this._events[eventname].splice(i , 1);
            }
        }
    },    
 
    removeAllListener:function(eventname:string) {
        if (typeof(this._events[eventname]) == "undefined") {
            var handlers = this._events[eventname];
            for (var i = 0; i < handlers.length; i++) {
                handlers[i] = null;
            }
        }
    },
 
    resetAllListener:function() {
        for (const key int this._events) {
            if (this._events.hasOwnProperty(key)) {
                delete this._events[key];
            }
        }
    },
        
    dispatchEvent:function(eventname:string, data:object) {
        console.log("eventname = " + eventname);
        if (typeof(this._events[eventname]) != "undefined") {
            var handlers = this._events[eventname];
            for (var i = 0; i < handlers.length; i++) {
                var handler = handlers[i];
                handler.callback.call(handler.target, data);
            }
        }
    },
};

使用  :   import {EventCenter, EventType} from "./Event";

添加事件监听:EventCenter.addListener(EventType.EVENT_NAME, this.callback, this);

销毁事件监听:EventCenter.removeListener(EventType.EVENT_NAME, this.callback, this);

发送事件消息:EventCenter.dispatchEvent(EventType.EVENT_NAME, data); 

你可能感兴趣的:(TypeScript,cocos,creator)