Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unbind an event bound with Ember.run.bind?

Tags:

ember.js

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?

like image 423
bummzack Avatar asked Jan 09 '23 04:01

bummzack


1 Answers

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);
    }
  }
});
like image 110
bummzack Avatar answered Feb 23 '23 02:02

bummzack