Infinite loop when using jQuery to trigger event on object with function of same name

Viewed 3805

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.

4 Answers
Related