(十)OpenLayers事件機(jī)制分析 OpenLayers中的事件封裝是其一大亮點(diǎn),非常值得學(xué)習(xí)。說到事件機(jī)制,在宏觀上不得不涉及控件OpenLayers.Control類、OpenLayers. Marker類、OpenLayers.Icon類等。是這樣,在外觀上控件通過Marker和Icon表現(xiàn)出來,而事件包含在控件之后,用他們自己的話說就是:The controls that wrap handlers define the methods that correspond to these abstract events 。順便再說一句,控件實(shí)現(xiàn)的核心是handler類,每個(gè)控件中都包含對(duì)handler的引用,通過active和deactive兩個(gè)方法,實(shí)現(xiàn)動(dòng)態(tài)的激活和注銷。 OpenLayers中的事件有兩種:一種是瀏覽器事件(比如onclick,onmouseup等),另一種是自定義的事件。自定義的事件像addLayer ,addControl等,不象瀏覽器事件會(huì)綁定相應(yīng)的dom節(jié)點(diǎn),它是與layer、map等關(guān)聯(lián)的。 OpenLayers中支持的瀏覽器事件類型有(以常量的形式提供的): BROWSER_EVENTS: [ "mouseover", "mouseout", "mousedown", "mouseup", "mousemove", "click", "dblclick", "resize", "focus", "blur" ] 看看構(gòu)造函數(shù)的的實(shí)現(xiàn)過程: 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)方法會(huì)將以數(shù)組eventTypes的每個(gè)元素為key建立哈希表listeners,表中每個(gè)鍵對(duì)應(yīng)一個(gè)數(shù)組。還會(huì)給this.eventHandler賦值,它實(shí)際只是一個(gè)包裝了triggerEvent事件觸發(fā)函數(shù)的方法,所有的事件,包括瀏覽器事件和自定義事件都是通過它來中轉(zhuǎn)的。然后initialize將所有的瀏覽器事件放入listeners中,并為其綁定相應(yīng)的dom節(jié)點(diǎn)element和this.eventHandler事件處理函數(shù)OpenLayers.Event.observe(element, eventType, this.eventHandler),節(jié)點(diǎn)上事件觸發(fā)的時(shí)候會(huì)把事件傳給this.eventHandler,它調(diào)用triggerEvent,從而將事件傳出來。 來看其他的成員函數(shù): addEventType:Add a new event type to this events object; attachToElement:把瀏覽器事件關(guān)聯(lián)到相應(yīng)的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參數(shù)是預(yù)先定義的回調(diào)函數(shù)。 unregister:注銷方法; remove:Remove all listeners for a given event type. triggerEvent:Trigger a specified registered event。 |
|