That title probably doesn't help much, I tried though. Anyway I ran into this extremely mysterious (and frustrating) bug resulting in a RangeError: Maximum call stack size exceeded
in some OO JS I'd written. Took me a couple hours but I finally got to the cause. Here's a simple example that will result in the same exception:
// Class
var Foo = function(){
// "Public" function
this.bar = function(){
console.log('loop!');
$(this).trigger('bar');
}
}
var foo = new Foo();
$(foo).trigger('bar');
Running this code will result in loop!
being logged to the console a ton of times before eventually resulting in the range exception.
Clearly there's something about jQuery's trigger
function I don't understand, and it boils down to this: why would foo's bar
function be called at all? Yes, the event name and the class's function name are the same, but I don't understand how the two are related.
You would need to use .triggerHandler
to mitigate this issue.
Per the jQuery docs:
Note: For both plain objects and DOM objects other than window, if a triggered event name matches the name of a property on the object, jQuery will attempt to invoke the property as a method if no event handler calls event.preventDefault(). If this behavior is not desired, use
.triggerHandler()
instead.
http://jsfiddle.net/bcsqF/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With