Path: blob/trunk/third_party/closure/goog/events/eventtarget.js
2868 views
// Copyright 2005 The Closure Library Authors. All Rights Reserved.1//2// Licensed under the Apache License, Version 2.0 (the "License");3// you may not use this file except in compliance with the License.4// You may obtain a copy of the License at5//6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS-IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314/**15* @fileoverview A disposable implementation of a custom16* listenable/event target. See also: documentation for17* {@code goog.events.Listenable}.18*19* @author [email protected] (Erik Arvidsson) [Original implementation]20* @see ../demos/eventtarget.html21* @see goog.events.Listenable22*/2324goog.provide('goog.events.EventTarget');2526goog.require('goog.Disposable');27goog.require('goog.asserts');28goog.require('goog.events');29goog.require('goog.events.Event');30goog.require('goog.events.Listenable');31goog.require('goog.events.ListenerMap');32goog.require('goog.object');33343536/**37* An implementation of {@code goog.events.Listenable} with full W3C38* EventTarget-like support (capture/bubble mechanism, stopping event39* propagation, preventing default actions).40*41* You may subclass this class to turn your class into a Listenable.42*43* Unless propagation is stopped, an event dispatched by an44* EventTarget will bubble to the parent returned by45* {@code getParentEventTarget}. To set the parent, call46* {@code setParentEventTarget}. Subclasses that don't support47* changing the parent can override the setter to throw an error.48*49* Example usage:50* <pre>51* var source = new goog.events.EventTarget();52* function handleEvent(e) {53* alert('Type: ' + e.type + '; Target: ' + e.target);54* }55* source.listen('foo', handleEvent);56* // Or: goog.events.listen(source, 'foo', handleEvent);57* ...58* source.dispatchEvent('foo'); // will call handleEvent59* ...60* source.unlisten('foo', handleEvent);61* // Or: goog.events.unlisten(source, 'foo', handleEvent);62* </pre>63*64* @constructor65* @extends {goog.Disposable}66* @implements {goog.events.Listenable}67*/68goog.events.EventTarget = function() {69goog.Disposable.call(this);7071/**72* Maps of event type to an array of listeners.73* @private {!goog.events.ListenerMap}74*/75this.eventTargetListeners_ = new goog.events.ListenerMap(this);7677/**78* The object to use for event.target. Useful when mixing in an79* EventTarget to another object.80* @private {!Object}81*/82this.actualEventTarget_ = this;8384/**85* Parent event target, used during event bubbling.86*87* TODO(chrishenry): Change this to goog.events.Listenable. This88* currently breaks people who expect getParentEventTarget to return89* goog.events.EventTarget.90*91* @private {goog.events.EventTarget}92*/93this.parentEventTarget_ = null;94};95goog.inherits(goog.events.EventTarget, goog.Disposable);96goog.events.Listenable.addImplementation(goog.events.EventTarget);979899/**100* An artificial cap on the number of ancestors you can have. This is mainly101* for loop detection.102* @const {number}103* @private104*/105goog.events.EventTarget.MAX_ANCESTORS_ = 1000;106107108/**109* Returns the parent of this event target to use for bubbling.110*111* @return {goog.events.EventTarget} The parent EventTarget or null if112* there is no parent.113* @override114*/115goog.events.EventTarget.prototype.getParentEventTarget = function() {116return this.parentEventTarget_;117};118119120/**121* Sets the parent of this event target to use for capture/bubble122* mechanism.123* @param {goog.events.EventTarget} parent Parent listenable (null if none).124*/125goog.events.EventTarget.prototype.setParentEventTarget = function(parent) {126this.parentEventTarget_ = parent;127};128129130/**131* Adds an event listener to the event target. The same handler can only be132* added once per the type. Even if you add the same handler multiple times133* using the same type then it will only be called once when the event is134* dispatched.135*136* @param {string|!goog.events.EventId} type The type of the event to listen for137* @param {function(?):?|{handleEvent:function(?):?}|null} handler The function138* to handle the event. The handler can also be an object that implements139* the handleEvent method which takes the event object as argument.140* @param {boolean=} opt_capture In DOM-compliant browsers, this determines141* whether the listener is fired during the capture or bubble phase142* of the event.143* @param {Object=} opt_handlerScope Object in whose scope to call144* the listener.145* @deprecated Use {@code #listen} instead, when possible. Otherwise, use146* {@code goog.events.listen} if you are passing Object147* (instead of Function) as handler.148*/149goog.events.EventTarget.prototype.addEventListener = function(150type, handler, opt_capture, opt_handlerScope) {151goog.events.listen(this, type, handler, opt_capture, opt_handlerScope);152};153154155/**156* Removes an event listener from the event target. The handler must be the157* same object as the one added. If the handler has not been added then158* nothing is done.159*160* @param {string} type The type of the event to listen for.161* @param {function(?):?|{handleEvent:function(?):?}|null} handler The function162* to handle the event. The handler can also be an object that implements163* the handleEvent method which takes the event object as argument.164* @param {boolean=} opt_capture In DOM-compliant browsers, this determines165* whether the listener is fired during the capture or bubble phase166* of the event.167* @param {Object=} opt_handlerScope Object in whose scope to call168* the listener.169* @deprecated Use {@code #unlisten} instead, when possible. Otherwise, use170* {@code goog.events.unlisten} if you are passing Object171* (instead of Function) as handler.172*/173goog.events.EventTarget.prototype.removeEventListener = function(174type, handler, opt_capture, opt_handlerScope) {175goog.events.unlisten(this, type, handler, opt_capture, opt_handlerScope);176};177178179/** @override */180goog.events.EventTarget.prototype.dispatchEvent = function(e) {181this.assertInitialized_();182183var ancestorsTree, ancestor = this.getParentEventTarget();184if (ancestor) {185ancestorsTree = [];186var ancestorCount = 1;187for (; ancestor; ancestor = ancestor.getParentEventTarget()) {188ancestorsTree.push(ancestor);189goog.asserts.assert(190(++ancestorCount < goog.events.EventTarget.MAX_ANCESTORS_),191'infinite loop');192}193}194195return goog.events.EventTarget.dispatchEventInternal_(196this.actualEventTarget_, e, ancestorsTree);197};198199200/**201* Removes listeners from this object. Classes that extend EventTarget may202* need to override this method in order to remove references to DOM Elements203* and additional listeners.204* @override205*/206goog.events.EventTarget.prototype.disposeInternal = function() {207goog.events.EventTarget.superClass_.disposeInternal.call(this);208209this.removeAllListeners();210this.parentEventTarget_ = null;211};212213214/** @override */215goog.events.EventTarget.prototype.listen = function(216type, listener, opt_useCapture, opt_listenerScope) {217this.assertInitialized_();218return this.eventTargetListeners_.add(219String(type), listener, false /* callOnce */, opt_useCapture,220opt_listenerScope);221};222223224/** @override */225goog.events.EventTarget.prototype.listenOnce = function(226type, listener, opt_useCapture, opt_listenerScope) {227return this.eventTargetListeners_.add(228String(type), listener, true /* callOnce */, opt_useCapture,229opt_listenerScope);230};231232233/** @override */234goog.events.EventTarget.prototype.unlisten = function(235type, listener, opt_useCapture, opt_listenerScope) {236return this.eventTargetListeners_.remove(237String(type), listener, opt_useCapture, opt_listenerScope);238};239240241/** @override */242goog.events.EventTarget.prototype.unlistenByKey = function(key) {243return this.eventTargetListeners_.removeByKey(key);244};245246247/** @override */248goog.events.EventTarget.prototype.removeAllListeners = function(opt_type) {249// TODO(chrishenry): Previously, removeAllListeners can be called on250// uninitialized EventTarget, so we preserve that behavior. We251// should remove this when usages that rely on that fact are purged.252if (!this.eventTargetListeners_) {253return 0;254}255return this.eventTargetListeners_.removeAll(opt_type);256};257258259/** @override */260goog.events.EventTarget.prototype.fireListeners = function(261type, capture, eventObject) {262// TODO(chrishenry): Original code avoids array creation when there263// is no listener, so we do the same. If this optimization turns264// out to be not required, we can replace this with265// getListeners(type, capture) instead, which is simpler.266var listenerArray = this.eventTargetListeners_.listeners[String(type)];267if (!listenerArray) {268return true;269}270listenerArray = listenerArray.concat();271272var rv = true;273for (var i = 0; i < listenerArray.length; ++i) {274var listener = listenerArray[i];275// We might not have a listener if the listener was removed.276if (listener && !listener.removed && listener.capture == capture) {277var listenerFn = listener.listener;278var listenerHandler = listener.handler || listener.src;279280if (listener.callOnce) {281this.unlistenByKey(listener);282}283rv = listenerFn.call(listenerHandler, eventObject) !== false && rv;284}285}286287return rv && eventObject.returnValue_ != false;288};289290291/** @override */292goog.events.EventTarget.prototype.getListeners = function(type, capture) {293return this.eventTargetListeners_.getListeners(String(type), capture);294};295296297/** @override */298goog.events.EventTarget.prototype.getListener = function(299type, listener, capture, opt_listenerScope) {300return this.eventTargetListeners_.getListener(301String(type), listener, capture, opt_listenerScope);302};303304305/** @override */306goog.events.EventTarget.prototype.hasListener = function(307opt_type, opt_capture) {308var id = goog.isDef(opt_type) ? String(opt_type) : undefined;309return this.eventTargetListeners_.hasListener(id, opt_capture);310};311312313/**314* Sets the target to be used for {@code event.target} when firing315* event. Mainly used for testing. For example, see316* {@code goog.testing.events.mixinListenable}.317* @param {!Object} target The target.318*/319goog.events.EventTarget.prototype.setTargetForTesting = function(target) {320this.actualEventTarget_ = target;321};322323324/**325* Asserts that the event target instance is initialized properly.326* @private327*/328goog.events.EventTarget.prototype.assertInitialized_ = function() {329goog.asserts.assert(330this.eventTargetListeners_,331'Event target is not initialized. Did you call the superclass ' +332'(goog.events.EventTarget) constructor?');333};334335336/**337* Dispatches the given event on the ancestorsTree.338*339* @param {!Object} target The target to dispatch on.340* @param {goog.events.Event|Object|string} e The event object.341* @param {Array<goog.events.Listenable>=} opt_ancestorsTree The ancestors342* tree of the target, in reverse order from the closest ancestor343* to the root event target. May be null if the target has no ancestor.344* @return {boolean} If anyone called preventDefault on the event object (or345* if any of the listeners returns false) this will also return false.346* @private347*/348goog.events.EventTarget.dispatchEventInternal_ = function(349target, e, opt_ancestorsTree) {350var type = e.type || /** @type {string} */ (e);351352// If accepting a string or object, create a custom event object so that353// preventDefault and stopPropagation work with the event.354if (goog.isString(e)) {355e = new goog.events.Event(e, target);356} else if (!(e instanceof goog.events.Event)) {357var oldEvent = e;358e = new goog.events.Event(type, target);359goog.object.extend(e, oldEvent);360} else {361e.target = e.target || target;362}363364var rv = true, currentTarget;365366// Executes all capture listeners on the ancestors, if any.367if (opt_ancestorsTree) {368for (var i = opt_ancestorsTree.length - 1; !e.propagationStopped_ && i >= 0;369i--) {370currentTarget = e.currentTarget = opt_ancestorsTree[i];371rv = currentTarget.fireListeners(type, true, e) && rv;372}373}374375// Executes capture and bubble listeners on the target.376if (!e.propagationStopped_) {377currentTarget = /** @type {?} */ (e.currentTarget = target);378rv = currentTarget.fireListeners(type, true, e) && rv;379if (!e.propagationStopped_) {380rv = currentTarget.fireListeners(type, false, e) && rv;381}382}383384// Executes all bubble listeners on the ancestors, if any.385if (opt_ancestorsTree) {386for (i = 0; !e.propagationStopped_ && i < opt_ancestorsTree.length; i++) {387currentTarget = e.currentTarget = opt_ancestorsTree[i];388rv = currentTarget.fireListeners(type, false, e) && rv;389}390}391392return rv;393};394395396