Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 871
Madbreaks Avatar asked Dec 11 '13 18:12

Madbreaks


1 Answers

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/

like image 57
Hacknightly Avatar answered Oct 27 '22 16:10

Hacknightly