Controller inheritance

I am using the following code in EVERY controller:

panels: Ember.inject.service(),
isOpen: Ember.computed.alias('panels.isOpen')

If i delete from all controllers and put only in the ApplicationController, shouldn’t work equal??? Because isn’t.

Thanks.

Go to official guide read about initializers, you will know how to inject once for every controller.

Controllers do not inherit from each other (do not extend each other would be more correct, as Javascript does not have the concept of inheritance). That is, unless you explicitly makes them. Routes form a hierarchy, in that each route knows about its parent. They do not extend each other either.

So what can you do? Well if it is only two lines, I would not care that much unless you either are planning to extend that common code, or put it in a lot of places. But if you do, you should extract a mixin.

// mixins/panels.js
export default Ember.Mixin.create({
    panels: Ember.inject.service(),
    isOpen: Ember.computed.readOnly('panels.isOpen'),
    // some other stuff related to panels
});

Now, in the controllers that need to access the panels or manipulate them in some way:

import PanelsMixin from 'mixins/panels';
export default Ember.Controller.extend(PanelsMixin, {
    // other stuff
});
1 Like