【发布时间】:2015-06-03 14:49:59
【问题描述】:
我正在编写一个 Mixin 来处理用户在视图/组件之外单击的情况。
这是混合:
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));
}),
});
【问题讨论】:
标签: ember.js