关闭

使用javascript和java模仿实现事件回调机制

58人阅读 评论(0) 收藏 举报
分类:

最近在学习nodejs中的eventEmitter类的时候。被它的事件注册回调机制的编程风格所吸引。于是决定使用javascript和java来模仿实现这种机制。

nodejs代码

//event.js 文件
var events = require('events'); 
var emitter = new events.EventEmitter(); 
emitter.on('someEvent', function(arg1, arg2) { 
	console.log('listener1', arg1, arg2); 
}); 
emitter.on('someEvent', function(arg1, arg2) { 
	console.log('listener2', arg1, arg2); 
}); 
emitter.emit('someEvent', 'arg1 参数', 'arg2 参数');

emitter使用on方法绑定事件"someEvent",然后注册对应的回调函数。

在javascript中这种方式屡见不鲜。$('#div_id').on('click', function(){});

一.javascript实现这种机制

1.服务端代码

	EventEmitter = function()
	{
		var eventsMap = {};
		var _this = this;
		
		var on = function( name, callback ){
	
			var callbackList = eventsMap[name] || [];
			
			callbackList.length > 0? 
				( eventsMap = eventsMap ):
				( eventsMap[name] = callbackList );
			
			return callbackList.push(callback);
		};
		
		var emit = function(){
			var name = Array.prototype.shift.call(arguments);
			
			var callbackList = eventsMap[name];
			
			for( var i = 0,len = callbackList.length; i < len; i++ ){
				
				var result = callbackList[i].apply( _this, arguments );
				if( result != void 0 ){
					return false;
				}
			}
			return true;
		}
		
		var remove = function(name){
			return delete eventsMap.name;
		}
		
		
		
		return {
			"on" : on,
			"emit" : emit,
			"remove": remove
		};
	}


2.客户端代码

var event = new EventEmitter();
	
	event.on("click", function( data ){
		console.log("click1...");
		console.log( data.name );
	});
	
	event.on("click", function( data ){
		console.log("click2...");
		console.log( data.name );
	});
	
	event.on("mouseover", function( data ){
		console.log("mouseover...");
		console.log( data.age + ":" + data.add );
	});

	event.emit( "click", {"name": 'lilei} );

	event.emit( "mouseover", {"age": 12, "add": "shanghai"} );

二.java实现这种机制

1.编写接口EventService

package inter;

public interface EventService {
	void on( String eventName, EventHandler e );
	
	void remove( String eventName );
	
	void trigger( String eventName );
}


2.编写接口EventHandler

package inter;

public interface EventHandler {
	void callback( EventService eventService );
}


3.编写服务端实现类EventEmitter

package interimpl;

import inter.EventService;
import inter.EventHandler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EventEmitter implements EventService {

	private Map< String, List<EventHandler> >  eventMap = new HashMap< String, List<EventHandler> >();
	
	@Override
	public void on(String eventName, EventHandler EventHandler) {
		
		List<EventHandler> callbackList = eventMap.get(eventName);
		
		if( null == callbackList ){
 			callbackList =  new ArrayList<EventHandler>();
		}

		if( callbackList.isEmpty() ){
			eventMap.put(eventName, callbackList);
		}
		
		callbackList.add(EventHandler);
	}

	@Override
	public void remove(String eventName) {

		eventMap.remove( eventName );
	}

	@Override
	public void trigger( String eventName ) {
		
		List<EventHandler> callbackList = eventMap.get(eventName);
		
		for( EventHandler inter : callbackList ){

			inter.callback(this);
		}
		
	}
}


4.编写测试客户端

package client;

import inter.EventService;
import inter.EventHandler;
import interimpl.EventEmitter;

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		EventEmitter event = new EventEmitter();
		
		event.on("click", new EventHandler() {
			
			@Override
			public void callback(EventService e) {

				System.out.println("click...");
				
				e.trigger("mouseover");
			}
		});
			
		event.on("mouseover", new EventHandler() {
			
			@Override
			public void callback(EventService EventService) {
				
				System.out.println("mouseover...");
			}
		});
		
		event.trigger("click");
		//event.trigger("mouseover");
	}

}
总结: 主要基于观察者的设计模式。采用客户端和服务端分离的思想。使用函数“on”对客户端的回调函数callback进行注册。采用callbackLIst对同一个事件上的回调函数进行存储。最后把每个事件所对应的各自的回调函数列表映射到map中。






0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:725次
    • 积分:102
    • 等级:
    • 排名:千里之外
    • 原创:10篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档