Reputation: 5875
I have a component that has to react to viewport changes.
The naive approach would be to just bind a jQuery resize listener, but that could mess with the Ember run loop.
The best practice approach is to use Ember.run.bind
This works just fine, but I wonder how to unbind such an event once the component is no longer active?
Upvotes: 4
Views: 1204
Reputation: 5875
Figured this out. Ember.run.bind
doesn't actually need an unbind method, you can just unbind the jQuery event.
Code example:
export default Ember.Component.extend({
_resizeListener: null,
didInsertElement: function(){
// keep a reference to the event listener
this._resizeListener = Ember.run.bind(this, this.preformLayout);
Ember.$(window).on('resize', this._resizeListener);
},
willDestroy: function(){
if(this._resizeListener){
// whenever component gets destroyed, unbind the listener
Ember.$(window).off('resize', this._resizeListener);
}
}
});
Upvotes: 9