-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
79 lines (71 loc) · 1.89 KB
/
index.js
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
(function(){
var EventPropReg = /^([a-zA-Z][$a-zA-Z0-9]+):([a-z]+)$/
var Bug = {
attach: function(obj){
iterateAndCallFuncOnMatch.call(obj, listen)
},
detach: function(obj){
iterateAndCallFuncOnMatch.call(obj, unlisten)
}
}
// Shims for CommonJS, Require.js, and just the browser
if (typeof module !== 'undefined' && module.exports){
module.exports = Bug
}else if (typeof define !== 'undefined' && define.amd){
define(function(){ return Bug })
}else if (typeof window !== 'undefined'){
window.Bug = Bug
}
function iterateAndCallFuncOnMatch(func){
for (var key in this){
var m
if (m = key.match(EventPropReg)){
var obj = this[m[1]]
var evt = m[2]
var value = this[key]
func.call(this, obj, evt, value)
}
}
}
function bind(fn, obj){
var fun = function(){
return fn.apply(obj, arguments)
}
return {
context: obj,
fun: fun
}
}
function listen(obj, evt, handler){
if (handler._bound){
if (obj === handler._bound.context) return
unlisten(obj, evt, handler)
}
if (!obj) return
handler._bound = bind(handler, this)
var fun = handler._bound.fun
if (obj.addEventListener){
obj.addEventListener(evt, fun)
}else if (obj.attachEvent){
obj.attachEvent('on' + evt, fun)
}else if (obj.on && obj.off){
obj.on(evt, fun)
}else if (obj.on && obj.removeListener){
obj.on(evt, fun)
}
}
function unlisten(obj, evt, handler){
if (!handler._bound) return
var fun = handler._bound.fun
if (obj.removeEventListener){
obj.removeEventListener(evt, fun)
}else if (obj.attachEvent){
obj.detachEvent('on' + evt, fun)
}else if (obj.on && obj.off){
obj.off(evt, fun)
}else if (obj.on && obj.removeListener){
obj.removeListener(evt, fun)
}
delete handler._bound
}
}());