OpenLayers中的事件封装是其一大亮点,非常值得学习。说到事件机制,在宏观上不得不涉及控件OpenLayers.Control类、OpenLayers. Marker类、OpenLayers.Icon类等。是这样,在外观上控件通过Marker和Icon表现出来,而事件包含在控件之后,用他们自己的话说就是:The controls that wrap handlers define the methods that correspond to these abstract events 。顺便再说一句,控件实现的核心是handler类,每个控件中都包含对handler的引用,通过active和deactive两个方法,实现动态的激活和注销。
OpenLayers中的事件有两种:一种是浏览器事件(比如onclick,onmouseup等),另一种是自定义的事件。自定义的事件像addLayer ,addControl等,不象浏览器事件会绑定相应的dom节点,它是与layer、map等关联的。
OpenLayers中支持的浏览器事件类型有(以常量的形式提供的):
BROWSER_EVENTS: [
"mouseover", "mouseout",
"mousedown", "mouseup", "mousemove",
"click", "dblclick",
"resize", "focus", "blur" ]
看看构造函数的的实现过程:
initialize: function (object, element, eventTypes, fallThrough) {
this.object = object;
this.element = element;
this.eventTypes = eventTypes;
this.fallThrough = fallThrough;
this.listeners = {};
// keep a bound copy of handleBrowserEvent() so that we can
// pass the same function to both Event.observe() and .stopObserving()
this.eventHandler = OpenLayers.Function.bindAsEventListener(
this.handleBrowserEvent, this
);
// if eventTypes is specified, create a listeners list for each
// custom application event.
if (this.eventTypes != null) {
for (var i = 0; i < this.eventTypes.length; i++) {
this.addEventType(this.eventTypes[i]);
}
}
// if a dom element is specified, add a listeners list
// for browser events on the element and register them
if (this.element != null) {
this.attachToElement(element);
}
}
可以这样理解:
initialize(object, element, eventTypes, fallThrough)方法会将以数组eventTypes的每个元素为key建立哈希表listeners,表中每个键对应一个数组。还会给this.eventHandler赋值,它实际只是一个包装了triggerEvent事件触发函数的方法,所有的事件,包括浏览器事件和自定义事件都是通过它来中转的。然后initialize将所有的浏览器事件放入listeners中,并为其绑定相应的dom节点element和this.eventHandler事件处理函数OpenLayers.Event.observe(element, eventType, this.eventHandler),节点上事件触发的时候会把事件传给this.eventHandler,它调用triggerEvent,从而将事件传出来。
来看其他的成员函数:
addEventType:Add a new event type to this events object;
attachToElement:把浏览器事件关联到相应的DOM元素上;
register: Register an event on the events object.
register: function (type, obj, func) {
if (func != null) {
if (obj == null) {
obj = this.object;
}
var listeners = this.listeners[type];
if (listeners != null) {
listeners.push( {obj: obj, func: func} );
}
}
}
其中,func参数是预先定义的回调函数。
unregister:注销方法;
remove:Remove all listeners for a given event type.
triggerEvent:Trigger a specified registered event。