my-javascript-simple-note-of-event

Event

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
40
var EventUtil = {
addHandler: funciton(element, type, handler){
if(element.addEventListener){
element.addEventListener(type,handler, false);
}else if(elent.attachEvent){
element.attachEvent('on'+type, handler);
}else{
element.["on" + type] = handler;
}
},
removeHandler: function(element, type, handler){
if(element.removeEventListener){
element.removeEventListener(type,handler);
}else if(element.detachEvent){
element.detachEvent('on' + type, handler);
}else{
element["on" + type] = null;
}
},
getEvent: function(event){
return event ? event : window.event
},
getTarget: function(event){
return event.target || event.srcElement;
},
preventDefault: function(event){
if(event.preventDefault()){
event.preventDefault();
} else{
event.retrunValue = false;
}
},
stopPropagation: function(event){
if(event.stopPropagation){
event.stopPropagation();
}else{
event.cancelBubble = false;
}
}
}

Event delegation

1
2
3
4
5
< ul id="myLinks"> 
< li id="goSomewhere"> Go somewhere</ li>
< li id="doSomething"> Do something</ li>
< li id="sayHi"> Say hi</ li>
</ ul>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var item1 = document.getElementById("goSomewhere");
var item2 = document.getElementById("doSomething");
var item3 = document.getElementById("sayHi");

EventUtil.addHandler(item1,'click',function(event){
window.open(
'https://support.wwf.org.uk/earth_hour/index.php?type=individual',
'_blank' // <- This is what makes it open in a new window.
);
});

EventUtil.addHandler(item1,'click',function(event){
document.title = "Changed title";
});

EventUtil.addHandler(item1,'click',function(event){
alert('hi');
});

Could be changed to

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var list = document.getElementById('myLinks');
EventUtil.addHandler(list,function(event){
var event = EventUtil.getEvent(event);
var target = EventUtil.getTarget(event);
switch(target.id){
case "doSomething":
document.title = "Changed title";
break;
case "goSomewhere":
window.open(
'https://support.wwf.org.uk/earth_hour/index.php?type=individual',
'_blank' // <- This is what makes it open in a new window.
);
break;
case "sayHi":
alert('hi');
break;
}
});

Another case

1
2
3
<div class="outter">
<input type="button" id="myBtn">
</div>

If we change the innerHtml of the outter div

1
2
3
4
5
var btn = document.getElementById('myBtn');
btn.onclick = function(){
var outterDiv = document.getElementById('outtter');
outterDiv.innerHtml = "processing........";
}

The listener of button is still there, so above code could be changed to

1
2
3
4
5
6
var btn = document.getElementById('myBtn');
btn.onclick = function(){
btn.onclick = null;
var outterDiv = document.getElementById('outtter');
outterDiv.innerHtml = "processing........";
}