1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- class EventMgr{
- constructor() {
- console.log('EventMgr初始化');
- this.events = {};
- }
- //注册事件
- registerEvent(eventName, func, target){
- if(eventName==null || !func || !target){
- return;
- }
- if(!this.events[eventName]){
- this.events[eventName] = [];
- }
- this.events[eventName].push({'target': target, 'func': func});
- }
- //移除事件
- removeEvent(eventName, func, target){
- if(eventName==null || !func || !target){
- return;
- }
- let handlers = this.events[eventName];
- if(!handlers) return;
- for(let i=0; i< handlers.length; i++){
- if(handlers[i] && handlers[i].func == func && handlers[i].target == target){
- handlers[i] = undefined;
- break;
- }
- }
- }
- //移除整个事件
- clearEvent(eventName){
- let handlers = this.events[eventName];
- if(!handlers) return;
- for(let i=0; i < handlers.length; i++){
- handlers[i] = undefined;
- }
- }
- //分发事件
- postEvent(eventName, params){
- let handlers = this.events[eventName];
- if(!handlers) return;
- for(let i=0; i< handlers.length; i++){
- if(handlers[i]){
- try{
- handlers[i].func.call(handlers[i].target, params);
- }catch(error){
- console.log(error.message);
- console.log(error.stack.toString());
- }
- }
- }
- }
-
- }
- let instance = null;
- EventMgr.getInstance = function(){
- if(!instance){
- instance = new EventMgr();
- }
- return instance;
- }
- module.exports = EventMgr;
|