1 // Copyright (c) 2010 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
6 * @fileoverview This contains an implementation of the EventTarget interface
7 * as defined by DOM Level 2 Events.
10 cr.define('cr', function() {
13 * Creates a new EventTarget. This class implements the DOM level 2
14 * EventTarget interface and can be used wherever those are used.
17 function EventTarget() {
20 EventTarget.prototype = {
23 * Adds an event listener to the target.
24 * @param {string} type The name of the event.
25 * @param {!Function|{handleEvent:Function}} handler The handler for the
26 * event. This is called when the event is dispatched.
28 addEventListener: function(type, handler) {
30 this.listeners_ = Object.create(null);
31 if (!(type in this.listeners_)) {
32 this.listeners_[type] = [handler];
34 var handlers = this.listeners_[type];
35 if (handlers.indexOf(handler) < 0)
36 handlers.push(handler);
41 * Removes an event listener from the target.
42 * @param {string} type The name of the event.
43 * @param {!Function|{handleEvent:Function}} handler The handler for the
46 removeEventListener: function(type, handler) {
49 if (type in this.listeners_) {
50 var handlers = this.listeners_[type];
51 var index = handlers.indexOf(handler);
53 // Clean up if this was the last listener.
54 if (handlers.length == 1)
55 delete this.listeners_[type];
57 handlers.splice(index, 1);
63 * Dispatches an event and calls all the listeners that are listening to
64 * the type of the event.
65 * @param {!cr.event.Event} event The event to dispatch.
66 * @return {boolean} Whether the default action was prevented. If someone
67 * calls preventDefault on the event object then this returns false.
69 dispatchEvent: function(event) {
73 // Since we are using DOM Event objects we need to override some of the
74 // properties and methods so that we can emulate this correctly.
76 event.__defineGetter__('target', function() {
80 var type = event.type;
82 if (type in this.listeners_) {
83 // Clone to prevent removal during dispatch
84 var handlers = this.listeners_[type].concat();
85 for (var i = 0, handler; handler = handlers[i]; i++) {
86 if (handler.handleEvent)
87 prevented |= handler.handleEvent.call(handler, event) === false;
89 prevented |= handler.call(this, event) === false;
93 return !prevented && !event.defaultPrevented;
99 EventTarget: EventTarget