【问题标题】:Angular.JS - Event is being triggered multiple timesAngular.JS - 事件被多次触发
【发布时间】:2016-02-01 17:53:16
【问题描述】:

代码:

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() 函数解决了这个问题。

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

这里是但是,一旦我在菜单外单击,控制台日志似乎会运行多次,具体取决于我单击 app-off-canvas-menu 汉堡包的次数。

任何人都可以从我的代码中看到任何明显的东西吗?

值得注意的是,我使用的是 angular,因此我可能必须以不同的方式解决这个问题。

【问题讨论】:

    标签: javascript jquery angularjs


    【解决方案1】:

    如果你点击类 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);
        }
      }
    };
    

    【讨论】:

    • 也许我理解错了,但我相信这就是我想要的。我只希望 .one() 函数运行一次。我不确定你的解决方案是什么。
    • 传奇,完美答案。谢谢
    猜你喜欢
    • 2013-07-06
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多