当前位置 : 主页 > 网络编程 > JavaScript >

CocosCreator 全局的消息事件

来源:互联网 收集:自由互联 发布时间:2021-06-30
全局的消息事件 let getTypeObj = function(type) { let types = []; if(type) { if(typeof(type) === 'string') { types.push(type); } else if(typeof(type) === 'object') { types = type; } else { return undefined; } return types; } else { re
全局的消息事件
let getTypeObj = function(type) {
    let types = [];

    if(type) {
        if(typeof(type) === 'string') {
            types.push(type);
        } else if(typeof(type) === 'object') {
            types = type;
        } else {
            return undefined;
        }
        return types;
    } else {
        return undefined;
    }
};

let Notification = {
    eventMap:[],
    on: function(type, callback, target) {

        let types = getTypeObj(type);
        if(!types) { return; }
        cc.log('types Array:'+JSON.stringify(types));
        for(let k in types) {
            let v = types[k];
            if(typeof(v) === 'string') {
                if (this.eventMap[type] === undefined) {
                    this.eventMap[type] = [];
                }
                this.eventMap[type].push({ callback: callback, target: target });
            } else {
                throw Error("Notification type error.");
            }
        }
        return {type: type, callback: callback};
    },

    emit: function(type, parameter) {
        let array = this.eventMap[type];
        if (array === undefined) return;

        for (let i = 0; i < array.length; i++) {
            let element = array[i];
            if (element) element.callback.call(element.target, parameter);
        }
    },

    off: function(type, callback) {
        let array = this.eventMap[type];
        if (array === undefined) return;

        for (let i = 0; i < array.length; i++) {
            let element = array[i];
            if (element && element.callback === callback) {
                array.splice(i, 1);
                break;
            }
        }
    },
    offType: function(type) {
        this.eventMap[type] = undefined;
    },

    offId: function(id) {
        if(id && id.type && id.callback) {
            let types = getTypeObj(id.type);
            if(!types) { return; }

            for(let k in types) {
                let v = types[k];
                if(typeof(v) === 'string') {
                    this.off(v, id.callback);
                } else {
                    throw Error("Notification type error.");
                }
            }
        }
    }
};
module.exports = Notification;
网友评论