Angular.JS - 多次触发事件

时间:2016-02-01 09:29:08

标签: javascript jquery angularjs

代码:

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汉堡包的次数。

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

值得注意的是,我正在使用棱角分叉,所以我可能不得不以不同的方式解决这个问题。

1 个答案:

答案 0 :(得分:2)

  

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

每次单击该类时,您将绑定另一个处理程序:

.one()

因此,当您在元素外部单击时,它将执行所有这些处理程序。

来自jQuery网站:

  

.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); } } }; 相同,只是处理程序在第一次调用后未绑定。

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

使用代码更新:

{{1}}