Ember, mixin to detect click outside of view/component

后端 未结 5 979
梦谈多话
梦谈多话 2021-01-06 05:48

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

This is the mixin:

App.ClickElsewhereMixin = Ember.Mixin.create({

  onC         


        
5条回答
  •  走了就别回头了
    2021-01-06 05:58

    You have two options:

    1. Use a closure
    2. Use bind

    Closure

    App.ClickElsewhereMixin = Ember.Mixin.create({
    
      onClickElsewhere: Ember.K,
    
      didRender: function() {
        this._super.apply(this, arguments);
        return $(document).on('click', function(this){ return this.get('onClickElsewhere'); }(this));
      },
    
      willDestroyElement: function() {
        this._super.apply(this, arguments);
        $(document).off('click', function(this){ return this.get('onClickElsewhere'); }(this));
      },
    });
    

    Bind

    App.ClickElsewhereMixin = Ember.Mixin.create({
    
      onClickElsewhere: Ember.K,
    
      didRender: function() {
        this._super.apply(this, arguments);
        return $(document).on('click', this.get('onClickElsewhere').bind(this));
      },
    
      willDestroyElement: function() {
        this._super.apply(this, arguments);
        $(document).off('click', this.get('onClickElsewhere').bind(this));
      },
    });
    

    However, not all browsers support bind yet.

    Also, I think you need to use sendAction instead of send in the component (http://guides.emberjs.com/v1.10.0/components/sending-actions-from-components-to-your-application/)

    Edit:

    jQuery.proxy uses call/apply underneath the covers. See this post for a discussion of call/apply vs bind.

提交回复
热议问题