Tomas
Tomas

Reputation: 1467

Ember one init for ALL routes

If I want to do something on route init, I use

MyRoute = Ember.Route.extend({
  init: function(){
    // do stuff
  }
})

What about if I want to run the same function for initialization of all routes. Is there a way to do it globally without going through each route individually ?

Upvotes: 0

Views: 179

Answers (3)

Tomas
Tomas

Reputation: 1467

Both answers are good, but require changing application code. In my case I want to use it for switching stylesheets so every route has it's own stylesheet. I need it only for development, and in production I would compile all stylesheets into one and remove the code which switches stylesheets.

In this case I found it's best to put your code in Ember core ( search for var Route = EmberObject.extend )

I also realized that for switching stylesheets it's better to have individual stylesheets not for routes, but for templates.

When I find out, I will post how to do it here: https://stackoverflow.com/questions/24068433/ember-change-stylesheet-for-every-template

Upvotes: 0

saygun
saygun

Reputation: 1438

Extend your base route:

MyRoute = Ember.Route.extend({
  init: function(){
    this._super();
    // do stuff
  }
});

OtherRoute = MyRoute.extend({
  init: function(){
    this._super();
  }
});

Upvotes: 1

GJK
GJK

Reputation: 37369

Indeed there is. Just use a mixin.

var InitializeMixin = Ember.Mixin.create({
    __init: function() {
        // do stuff
    }.on('init')
});

App.MyRoute = Ember.Route.extend(InitializeMixin, {

});

Just mix it into any route you want to do the setup in. Also note that I used on('init') instead of overriding the init function. This is a little cleaner (I think) because you don't have to call this._super().

Upvotes: 2

Related Questions