Praveen Kumar
Praveen Kumar

Reputation: 1016

Ember Component cleanup code

just imagine there are more components rendered in web page, and when i click a link, i route to home page, which fills the entire page. (means all components gone in UI)

What are all the things i should make sure to clean up to avoid memory leaks?

Few examples:

If i used Ember.addObserver in component's didInsertElement, i should remove it using Ember.removeObserver in willDestroyElement method.

And any event handlers attached should be detached.

Can i get some more examples / link to see what are all the things i should cleanup and where?

Upvotes: 1

Views: 645

Answers (1)

user663031
user663031

Reputation:

The ideal is to write your code so that no clean-up is required.

For instance, if you define an observer as

observeWhatever: Ember.observer('whatever', function() {...

no special teardown is necessary. In the same way, if you define an event handler as

click: function(event) { ...

then no tear-down is necessary. But what if you want to listen to a DOM event on some element within your component? We often see people who can't remember whether they're programming in Ember or jQuery do things like:

setupWhatever: function() {
  Ember.$('.foo.bar.baz').on('click', function() { alert('baz clicked!'); });
}.on('init')

This is pretty much an anti-pattern, and not just because it will need to be torn down. It is completely jumbling up how to refer to parts of the app, and how to set up callbacks, and how to handle actions. The thing you are referring to as .foo.bar.baz should be its own component, which sets up its own listener at the component level. It would send an action, which would be handled as follows:

{{foo-bar-baz action=(action 'bazClicked')}}

actions: {
  bazClicked() { alert('baz clicked'); }
  ...
}

If you want to set up a hook, such as

listen: Ember.on('message', function() ...

that will also be torn down for you.

If I used Ember.addObserver in component's didInsertElement, I should remove it using Ember.removeObserver in willDestroyElement method.

What kind of observer would you be setting up in didInsertElement? Excessive use of didInsertElement is also an anti-pattern. If you are using Ember correctly, it should hardly ever be necessary. A possible exception is initializing a jQuery add-on, if you are so unfortunate as to be using one of those.

If for whatever reason you are working with timers, you may need to cancel them on exit.

Upvotes: 3

Related Questions