Ember ControllerMixin example


#1

I have 2 different routes, which kind of uses similar controller attributes/CPs How do I implement a common controller mixin for both the routes ?

Any example would be really great.


#2

Hi Harimath,

The Ember.ControllerMixin is a private class not extandable. I made some kind of research for my personnal purpose.

I find two way to do the job.

The extend way :
You can create a controller that extend for another one.

App.ControllerGeneric = Ember.Controller.extend({
  isExpanded: false,

  actions: {
    toggleBody() {
      this.toggleProperty('isExpanded');
    }
  }
});

App.IndexController = App.ControllerGeneric.extend();

App.ListController = App.ControllerGeneric.extend({
  isExpanded: true
});

The mixin way :
You can create a mixin to use when you create a new controller.

App.GenericControllerMixin = Ember.Mixin.create({
  isExpanded: false,

  actions: {
    toggleBody() {
      this.toggleProperty('isExpanded');
    }
  }
});

App.IndexController =  Ember.Controller.extend(App.GenericControllerMixin);

App.ListController = Ember.Controller.extend(App.GenericControllerMixin, {
  isExpanded: true
});

Sorry for my poor english.


#3

Thanks for the reply. Your English is perfect. Don’t worry :slight_smile:

When we use a mixin, is it necessary to declare attributes explicitly at the class level (i.e. in the mixin) OR we can directly declare it in the controller extending that mixin ?

What is the recommended way ?


#4

There is no restriction in property declarations.

You can declare the properties anywhere (either in Mixins or in Controllers) but when you declare a property at both the places, controller’s value will be overridden by Mixins (property) value.

One more, @Property declaration at Mixins will reduce code redanduncy.