javascript – 使用jQuery触发具有相同功能的对象上的事件时的无限循环

前端之家收集整理的这篇文章主要介绍了javascript – 使用jQuery触发具有相同功能的对象上的事件时的无限循环前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这个头衔可能没多大帮助,我试过了.无论如何,我遇到了这个极其神秘(令人沮丧)的错误,导致了一个RangeError:我编写的一些OO JS中超出了最大调用堆栈大小.花了我几个小时,但我终于找到了原因.这是一个简单的例子,它将导致相同的异常:
// Class
var Foo = function(){
    // "Public" function
    this.bar = function(){
        console.log('loop!');
        $(this).trigger('bar');
    }
}

var foo = new Foo();
$(foo).trigger('bar');

运行此代码将导致循环!在最终导致范围异常之前,多次登录到控制台.

显然有一些关于jQuery的触发器功能我不明白,可归结为:为什么foo的bar函数会被调用?是的,事件名称和类的函数名称是相同的,但我不明白这两者是如何相关的.

解决方法

您需要使用.triggerHandler来缓解此问题.

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/

原文链接:https://www.f2er.com/jquery/153829.html

猜你在找的jQuery相关文章