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?
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);
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With