I was playing with a fiddle earlier today while trying to answer a question and found a confusing thing. Being a JS newbie I am not being able to debug whats going wrong myself. I even tried to check the source0 of $.fn.show in jQuery source but couldn’t figure out whats going wrong.
HTML:
<input type='text' id='dataBox'/>
<input type='button' value='toggle' id='toggleButton' />
jQuery code:
jQuery(function ($) {
var _oldShow = $.fn.show;
$.fn.show = function (speed, oldCallback) {
return $(this).each(function () {
var obj = $(this),
newCallback = function () {
if ($.isFunction(oldCallback)) {
oldCallback.apply(obj);
}
obj.trigger('afterShow');
};
obj.trigger('beforeShow');
if(speed)
_oldShow.apply(obj, [speed,newCallback]);
else
_oldShow.apply(obj, [newCallback]);
});
}
});
$('#dataBox').bind('beforeShow', function () {
alert('beforeShow');
});
$('#toggleButton').click(function(){
$('#dataBox').show();
});
The problem is for some mistake that I did, is causing this line to execute infinite number of times
obj.trigger(‘beforeShow’);
and hence the alert in this block
$('#dataBox').bind('beforeShow', function () {
alert('beforeShow');
});
seems not to stop.
Irrespect of what I am trying to do or if this can be done any other way, can someone please explain what I am doing wrong here. I have been trying for several hours but couldn’t figure out.
The problem with the above code is that at some point jQuery calls the
$.fn.showfrom within itself and that creates the infinite loop. So the proper way to prevent that is to do some argument checking like follows:This works fine and the events are fired properly.
The block which is preventing the infinite loop is this
What this is doing is, calling the original function and returning in cases jQuery calls
$.fn.showmultiple times(jQuery seems to be doing so for some reason).Working Fiddle