Ember,mixin 来检测视图/组件之外的点击 [英] Ember, mixin to detect click outside of view/component

查看:21
本文介绍了Ember,mixin 来检测视图/组件之外的点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 Mixin 来处理用户在视图/组件之外单击的情况.

I'm writing a Mixin to handle when user clicks outside of a view/component.

这是混合:

App.ClickElsewhereMixin = Ember.Mixin.create({

  onClickElsewhere: Ember.K,

  didRender: function() {
    this._super.apply(this, arguments);
    return $(document).on('click', this.get('onClickElsewhere'));
  },

  willDestroyElement: function() {
    this._super.apply(this, arguments);
    $(document).off('click', this.get('onClickElsewhere'));
  },
});

我在我的组件中使用它:

I use it in my component:

onClickElsewhere: function() {
    this.send('exitEditMode');
},

但是当我运行它时,我得到:

But when I run it, I get:

TypeError: this.send is not a function

我怎样才能保持 this 上下文?

How can I keep the this context?

为了让读者更容易,这里是工作的 Mixin:

just to make it easier for the reader, here the working Mixin:

App.ClickElsewhereMixin = Ember.Mixin.create({

  onClickElsewhere: Ember.K,

  setupListener: Ember.on('didRender', function() {
    // Set an event that will be fired when user clicks outside of the component/view
    return $(document).on('click', $.proxy(this.get('onClickElsewhere'), this));
  }),

  removeListener: Ember.on('willDestroyElement', function() {
    // Clean the previously defined event to keep events stack clean
    return $(document).off('click', $.proxy(this.get('onClickElsewhere'), this));
  }),
});

推荐答案

当前的答案没有检查点击是否真的在元素之外——点击组件也会触发回调.

The current answer doesn't check whether the click was actually outside of the element – a click on the component will also trigger the callback.

这是一个更新的版本:

export default Ember.Mixin.create({
  onOutsideClick: Ember.K,

  handleOutsideClick: function(event) {
    let $element = this.$();
    let $target = $(event.target);

    if (!$target.closest($element).length) {
      this.onOutsideClick();
    }
  },

  setupOutsideClickListener: Ember.on('didInsertElement', function() {
    let clickHandler = this.get('handleOutsideClick').bind(this);

    return Ember.$(document).on('click', clickHandler);
  }),

  removeOutsideClickListener: Ember.on('willDestroyElement', function() {
    let clickHandler = this.get('handleOutsideClick').bind(this);

    return Ember.$(document).off('click', clickHandler);
  })
});

这篇关于Ember,mixin 来检测视图/组件之外的点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆