I’m a little confused, when I try to Bind a Function to an event (like click) in IE7,IE9, Chrome 18, Firefox 12 it’s work great, but when I try to remove the associated function to the event, only IE7 and Firefox are capable of dis-attach the function.
This is the code i’m using, what i’v doing wrong ??
bindEvent:function(el,evtType,fn){
if(el.addEventListener){
el.addEventListener(evtType,fn,false);
} else {
if(el.attachEvent){
var _el=el;
var f = function(){fn.call(_el,window.event);}
el.attachEvent( 'on'+evtType, f);
el[fn.toString()+evtType]=f;
//el.attachEvent('on'+evtType,fn) ;
} else {
el['on'+evtType]=fn;
}
}
return el;
},
removeEvent: function(el,evtType, fn ) {
if( el.removeEventListener){
el.removeEventListener( evtType, fn, false );
}else if(el.detachEvent){
el.detachEvent('on'+evtType,el[fn.toString()+evtType]);
el[fn.toString()+evtType]=null;
}else{
el['on'+evtType]=function(){};
}
return el;
}
My codes to test this are:
var a = document.getElementById('just_a_div');
bindEvent(a,'click',function(){alert('Hi There');});
And to try to remove i use almost the same:
removeEvent(a,'click',function(){alert('Hi There');});
Any Ideas or some pre-made Snippets that can do this task efficiently on all browsers??
Hope a solution can appear, Eternally grateful.
Your code works in my example in IE8, firefox and chrome (the event will be removed after five seconds). Maybe you have an error in your testcase? Can you show us your testcase?
=== UPDTAE ===
In javascript functions are never the same also when they have the same parameters and content. Try:
alert(function(){alert('Hi There');} == function(){alert('Hi There');});The result isfalse.Reverences to functions are equal, if they reverences to the same function. So
var fn = function() { alert('clicked'); }; alert(fn == fn);istrue.You should use the same refernce to a function in the
bindEventandremoveEventfunction like in my example.