2016-02-01 64 views
2

代码:Angular.JS - 事件被多次触发

scope.offCanvasShow = function ($event) { 
    $('.app-off-canvas-menu').toggleClass('show'); 
    // Prevents default functionality of a element 
    // In this instance, this prevents the anchor from reloading the page on click. 
    $event.preventDefault(); 
    $event.stopPropagation(); 

    $(document).one('touchstart click', offCanvasHandler); 

    /** 
    * Checks to see if the event target isn't .off-canvas-menu or has off-canvas-menu as a parent then removes the 
    * show class. 
    * @param event - is the event of the function 
    */ 
    function offCanvasHandler(event) { 
    console.log('hello'); 
    if (!$(event.target).closest('.app-off-canvas-menu').length) { 
     $('.app-off-canvas-menu').removeClass('show'); 
     $(document).off('touchstart click', offCanvasHandler); 
    } else { 
    $(document).one('touchstart click', offCanvasHandler); 
    } 
    } 
}; 

这是一个简单的关闭帆布下拉菜单。我有这个冒泡的奇怪问题。我认为我修复了.one()函数。

如果该类应用关闭帆布菜单上单击几次,然后离开菜单打开,单击菜单关闭这就是我想要的菜单之外。

但是,一旦我点击菜单外部,看起来控制台日志会运行多次,具体取决于我点击应用程序画布菜单汉堡包的次数。

任何人都可以看到什么我的代码区分明显?

它值得指出的是,我使用的角度,从而有可能我也去了解这个以不同的方式。

回答

2

如果您点击课程app-off-canvas-menu几次,然后将菜单保持打开状态并单击菜单外部,菜单将关闭,这是我想要的。

每次你在类单击要绑定另一个处理程序:

$(document).one('touchstart click', offCanvasHandler); 

所以当你点击该元素外,将执行所有的处理程序。

从jQuery网站:

.one()方法等同于.on(),不同之处在于处理程序是其第一调用之后未结合的。

所以,你不绑定一次,它只能运行一次。这可能会造成混乱。


更新,代码:

var isBound = false; 
scope.offCanvasShow = function ($event) { 
    $('.app-off-canvas-menu').toggleClass('show'); 
    // Prevents default functionality of a element 
    // In this instance, this prevents the anchor from reloading the page on click. 
    $event.preventDefault(); 
    $event.stopPropagation(); 

    if(!isBound) { 
     $(document).one('touchstart click', offCanvasHandler); 
     isBound = true; 
    } 

    /** 
     * Checks to see if the event target isn't .off-canvas-menu or has off-canvas-menu as a parent then removes the 
     * show class. 
     * @param event - is the event of the function 
    */ 
    function offCanvasHandler(event) { 
     console.log('hello'); 
     if (!$(event.target).closest('.app-off-canvas-menu').length) { 
     $('.app-off-canvas-menu').removeClass('show'); 
     $(document).off('touchstart click', offCanvasHandler); 
    } else { 
     $(document).one('touchstart click', offCanvasHandler); 
    } 
    } 
}; 
+0

也许我有错误理解,但我相信,这是我想要的。我只想要.one()函数运行一次。我不确定你的解决方案是什么。 –

+0

传奇,完美答案。谢谢 –