Trick that I’m going to talk about may look obvious for experienced developers, but I hope this post will be useful for someone new to it.
If you developed one or two ember components or read official guide, you know that component has lifecycle hooks which can be used to manipulate DOM and integrate components with jquery plugins (usually didInsertElement and willDestroyElement used). I’d say that this (integration with jquery plugins) is a most common usecase of components. But did you ever think about using a component for something other than creating new UI elements?
The thing is, inside didInsertElement (and in willDestroyElement, too) you can manipulate any DOM elements, including those that are outside of your application’s templates. For example, you can:
- Use a component to add/remove css class on body element. Useful for theming or when you want to change a look of application completely for certain routes.
- Use a component to add/remove css class from root element of application.
import Ember from 'ember'; export default Ember.Component.extend({ parentClass: '', didInsertElement() { this.$().parent().addClass(this.get('parentClass')); } });
Just drop this component in
application.hbs
, somewhere in the beginning of template - Use a component to remove some elements after ember application is loaded. Ember-load (a simple loading indicator, while your static assets download, and your Ember.js app starts up) uses this method to remove loading animation.
In all these cases component’s template is empty, so nothing (only empty div) will be rendered.
Of course, it’s a good practice to change only component’s own DOM in lifecycle hooks. But in examples above it works very well.
Featured image source – pxhere.com