首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular.JS -事件被多次触发

Angular.JS -事件被多次触发
EN

Stack Overflow用户
提问于 2016-02-01 09:29:07
回答 1查看 247关注 0票数 2

代码:

代码语言:javascript
复制
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()函数。

如果你点击类应用程序-画布菜单几次,然后保持菜单打开,然后点击菜单外面的菜单关闭,这就是我想要的。

但是,当我在菜单外单击时,控制台日志似乎会多次运行,这取决于我点击了应用程序的次数--画布菜单上的汉堡包。

有人能从我的代码中看到明显的东西吗?

值得注意的是,我使用的角度,所以它可能是可能的,我必须采取不同的方式。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-01 09:33:42

如果你点击类应用程序-画布菜单几次,然后保持菜单打开,然后点击菜单外面的菜单关闭,这就是我想要的。

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

代码语言:javascript
复制
$(document).one('touchstart click', offCanvasHandler);

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

来自jQuery网站:

.one()方法与.on()完全相同,只不过在第一次调用之后处理程序是不绑定的。

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

用代码更新:

代码语言:javascript
复制
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);
    }
  }
};
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35126977

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档