Created
December 30, 2013 05:47
-
-
Save vitrum/8178266 to your computer and use it in GitHub Desktop.
Bind and unbind even listener. http://www.niumowang.org/javascript/event-listener/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div id="wrap"> | |
click here | |
</div> | |
<a onclick="bindFn()" href="javascript:;" class="btn">bind</a> | |
<a onclick="unbindFn()" href="javascript:;" class="btn">unbind</a> | |
<script> | |
var handleHash = {}; | |
var bind = (function() { | |
if (window.addEventListener) { | |
return function(el, type, fn, capture) { | |
el.addEventListener(type, function(){ | |
fn(); | |
handleHash[type] = handleHash[type] || []; | |
handleHash[type].push(arguments.callee); | |
}, capture); | |
}; | |
} else if (window.attachEvent) { | |
return function(el, type, fn, capture) { | |
el.attachEvent("on" + type, function(){ | |
fn(); | |
handleHash[type] = handleHash[type] || []; | |
handleHash[type].push(arguments.callee); | |
}); | |
}; | |
} | |
})(); | |
var unbind = (function(){ | |
if (window.addEventListener) { | |
return function(el, type ) { | |
if(handleHash[type]){ | |
var i = 0, len = handleHash[type].length; | |
for (i; i<len ; i += 1){ | |
el.removeEventListener(type, handleHash[type][i]); | |
} | |
}; | |
}; | |
} else if (window.attachEvent) { | |
return function(el, type) { | |
if(handleHash[type]){ | |
var i = 0, len = handleHash[type].length; | |
for (i; i<len ; i += 1){ | |
el.detachEvent("on" + type, handleHash[type][i]); | |
} | |
}; | |
}; | |
} | |
})(); | |
var obj = document.getElementById('wrap'); | |
function bindFn(){ | |
bind(obj,'click',function(){ | |
alert ('click'); | |
}); | |
bind(obj,'click',function(){ | |
alert ('click2'); | |
}); | |
}; | |
function unbindFn(){ | |
unbind(obj,'click'); | |
}; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment