HTML and CSS Reference
In-Depth Information
addEventListener()
Allows us to add a listener (subscriber) for a particular event
dispatch()
Allows us to send events to listeners
removeEventListener()
removeEventListener()
Allows us to remove a listener when it is no longer needed
By defining all the preceding methods as properties of the
EventDispatcher
prototype
(
EventDispatcher.prototype.addEventListener()
),anotherclasswillbeabletousethis
class as a base class and inherit all of them.
//Adapted from code Copyright (c) 2010 Nicholas C. Zakas. All rights reserved.
//MIT License
function
function
EventDispatcher
(){
this
this
.
_listeners
=
{};
}
EventDispatcher
.
prototype
.
addEventListener
=
function
function
(
type
,
listener
){
iif
(
typeof
typeof this
this
.
_listeners
[
type
]
==
"undefined"
){
this
this
.
_listeners
[
type
]
=
[];
}
this
this
.
_listeners
[
type
].
push
(
listener
);
}
EventDispatcher
.
prototype
.
dispatch
=
function
function
(
event
){
iif
(
typeof
typeof
event
==
"string"
){
event
=
{
type
:
event
};
}
iif
(
!
event
.
target
){
event
.
target
=
this
this
;
}
iif
(
!
event
.
type
){
//false
throw
throw new
new
Error
(
"Event object missing 'type' property."
);
}
iif
(
this
this
.
_listeners
[
event
.
type
]
instanceof
instanceof
Array
){
var
var
listeners
=
this
this
.
_listeners
[
event
.
type
];
for
for
(
var
var
i
=
0
,
len
=
listeners
.
length
;
i
<
len
;
i
++
){
listeners
[
i
].
call
(
this
this
,
event
);
}
}
}