gpt4 book ai didi

ember.js - Ember,mixin 来检测 View /组件之外的点击

转载 作者:行者123 更新时间:2023-12-02 05:15:21 24 4
gpt4 key购买 nike

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

这是混合:

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'));
},
});

我在我的组件中使用它:
onClickElsewhere: function() {
this.send('exitEditMode');
},

但是当我运行它时,我得到:
TypeError: this.send is not a function

我怎样才能保留 this语境?

解决方案:

只是为了让读者更容易,这里是工作的 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));
}),
});

最佳答案

当前的答案不检查点击是否实际上在元素之外——对组件的点击也会触发回调。

这是一个更新的版本:

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.js - Ember,mixin 来检测 View /组件之外的点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30623530/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com