/******************************************************************************* * * Nx事件服务 * * * * 2021.12.10 ******************************************************************************/ const NxObject = require( "nx.object" ); var nxEventor = cc.Class( { extends: NxObject, name: "nxEventor", // 初始化 initialize: function( _args ) { // USPER if( !this._super( _args ) ) { return false; } this.binders = {}; // 全局服务开启 nx.event = this; return true; }, // 销毁 uninitialize: function() { this.clear(); // 全局服务关闭 nx.event = null; // USPER return this._super(); }, // 是否存在监听 isbinded: function( _binder ) { return this.binders[ _binder ] ? true : false; }, // 监听 bind: function( _binder, _lst ) { var key = nx.factory.getUUID( _binder, true ); if( nx.dt.strEmpty( key ) ) { nx.logger.error( "[事件]监听事件失败,无效的监听对象!" + key ); return false; } if( this.binders[ key ] ) { nx.logger.error( "[事件]监听关键字重复!" + key ); return false; } if( !nx.dt.arrGood( _lst ) ) { nx.logger.error( "[事件]监听事件失败,序列无效!" + key ); return false; } var bds = {}; for( let i in _lst ) { let bd = _lst[ i ]; let id = "" + bd[0]; if( nx.dt.strEmpty( id ) || !nx.dt.fnGood( bd[ 1 ] ) ) { nx.logger.error( "[事件]监听事件失败,无效的监听项!" + key ); return false; } bds[id] = bd[1]; } this.binders[ key ] = bds; nx.logger.debug( "[事件]增加监听:", key ); return true; }, // 解除 unbind: function( _binder ) { var key = nx.factory.getUUID( _binder, false ); if( nx.dt.strEmpty( key ) ) { nx.logger.error( "[事件]解除监听事件失败,无效的监听对象!" + key ); return false; } if( this.binders[ key ] ) { nx.logger.debug( "[事件]解除监听:", key ); delete this.binders[ key ]; } return true; }, // 发送 send: function( id, args, log = true ) { id = id + ''; if( nx.dt.strEmpty( id ) ) { nx.logger.error( "[事件]消息发送失败,参数非法!" ); return false; } if( log ) { nx.logger.debug( "[事件]发布:%s 参数:%s", id, args ? nx.dt.enjson( args ) : "" ); } nx.dt.trycatch( () => { for( var k in this.binders ) { var bs = this.binders[ k ]; if( typeof ( bs[ id ] ) == "function" ) { bs[ id ]( args ); } } } ); return true; }, // 清理 clear: function() { this.binders = {}; } } ); module.exports = nxEventor;