How to deal with components on app level?


#1

I’m tying to find the best practice concearning components that exist on app level and somehow have to respond to interaction on a lower level.

For example, I have a topbar component that is set in the application template. The topbar contains a title, a general pofile button and (has room for) context dependent buttons. According to the current route, the title and optional context buttons should change. Let’s say the login route should set the title to “welcome”, and the dashboard route should set the title to “Dashboard” and supply some buttons like “Add a new whatever”.

At first, I had the topbar assigned to window.topBar in the application controller, so I could access it directly from any route view. But this feels a bit dirty and highly unpractical now that the route is rendered before the application controller/template in the latest Ember release.

So, what is the best way to deal with this kind of situation in your opinion?


#2

You should have the top bar component observe properties on your app’s ApplicationController, and mutate those properties using actions. Quick example:

// app/controllers/application.js
export default Ember.Controller.extend({
  title: 'My App Name'
});

// app/routes/application.js
export default Ember.Route.extend({
  actions: {
    setTitle: function(title) {
      this.controller.set('title', title);
    }
  }
});

// app/templates/application.hbs
{{top-bar title=title}}

Should be everything you need. I do something similar for links in my app’s nav bar, letting the nav-bar component observe a navLinks property on the controller that looks like this:

navLinks: [
  {route: 'index', name: 'Home'},
  {route: 'foo.bar', name: 'Foo Bar'}
]