2016-02-01 63 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

傳奇,完美答案。謝謝 –