《JavaScript高级程序设计》学习-22.4-自定义事件

自定义事件基本模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
function EventTarget(){
this.handlers = {};
}

EventTarget.prototype = {
constructor: EventTarget,

addHandler: function(type, handler){
if (typeof this.handlers[type] == "undefined"){
this.handlers[type] = [];
}

this.handlers[type].push(handler);
},

fire: function(event){
if (!event.target){
event.target = this;
}
if (this.handlers[event.type] instanceof Array){
var handlers = this.handlers[event.type];
for (var i=0, len=handlers.length; i < len; i++){
handlers[i](event);
}
}
},
removeHandler: function(type, handler){
if (this.handlers[type] instanceof Array){
var handlers = this.handlers[type];
for (var i=0, len=handlers.length; i < len; i++){
if (handlers[i] === handler){
break;
}
}

handlers.splice(i, 1);
}
}
};

使用EventTarget类型的自定义事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function handleMessage(event) {
alert("Message received: " + event.message);
}

var target = new EventTarget();

target.addHandler("message", handleMessage);

target.fire({
type: "message",
message: "Hello world!"
});

target.removeHandler("message", handleMessage);

target.fire({
type: "message",
message: "Hello world!"
});

其它对象继承EventTarget

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
function object(o) {
function F() {}
F.prototype = o;
return new F();
}

function inheritPrototype(subType, superType) { //使用寄生组合继承
var prototype = object(superType.prototype); //create object
prototype.constructor = subType; //augment object
subType.prototype = prototype; //assign object
}

function Person(name, age) {
EventTarget.call(this);
this.name = name;
this.age = age;
}

inheritPrototype(Person, EventTarget);

Person.prototype.say = function(message) {
this.fire({
type: "message",
message: message
});
};



function handleMessage(event) {
alert(event.target.name + " says: " + event.message);
}

var person = new Person("Nicholas", 29);

person.addHandler("message", handleMessage);

person.say("Hi there.");