Skip to content

Instantly share code, notes, and snippets.

@vitrum
Created December 30, 2013 05:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vitrum/8178266 to your computer and use it in GitHub Desktop.
Save vitrum/8178266 to your computer and use it in GitHub Desktop.
<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