Setting page title with ember.js

2020-02-04 07:03发布

What is the best way to set the page's title, so that when transitioning between urls, the title will reflect the new state? Is there a way to set the Router to do this?

I want a method that allows me to set a page title schema for each state. So, if the route has parameters, they will be passed into the pageTitle:

sessions : Ember.Route.extend({
       route:"/sessions",
       connectOutlets : function(router) {
           //...
       },
       pageTitle:function(){
            return "Sessions";
       },
   })

I'm open to any suggestions as to how it is best to implement this type of functionality on the Model or someplace else.

标签: ember.js
7条回答
来,给爷笑一个
2楼-- · 2020-02-04 08:00

The previous answer was applicable for an old version of Ember. After several changes the Framework has reached version 1.0 RC2 and it's close to be final, so I decided to update this answer.

As an example, please look into the Routes defined in this fiddle: http://jsfiddle.net/schawaska/dWcUp/

The idea is the same as the previous answer, just in a different way since the Routing API has changed considerably.

The Route below, uses the activate hook to set the title of the document via jQuery:

App.ProductRoute = Em.Route.extend({
    activate: function() {
        $(document).attr('title', 'Auto Web Shop - Product');
    }
});

Edit: As noted in the comment section:

FYI activate is the API method, rather than enterpauldechov


This answer was given in a previous version of Ember and it no longer applies.

Inside your connectOutlets you can do something as simple as using jQuery to modify the document's title attribute:

[...]
home: Em.Route.extend({
    route: '/',
    connectOutlets: function (router, context) {                
        // router.set('navbarController.selected', 'home');                     
        router.get('applicationController')
              .connectOutlet('home');                     

        $(document).attr('title', 'YOUR TITLE GOES HERE');
    }
}),                
[...]

But you'd have to do this for every route.

In case you have something like a navbar controller that sets the selected nav menu item, you watch the selected property to both bind the "active" or "selected" css class to the nav item and set the page title; or you could have a property just for the title on the navitem model that you'd pass through the context (but I believe you'd have to handle this in the view and transition to the route from there).

Anyway, this is just to show one of the possible ways to set the page title.

EDIT: I've modified an existing fiddle to do that. Take a look at the method navigateTo in the router: http://jsfiddle.net/schawaska/hEx84/ (to see it running go here http://jsfiddle.net/schawaska/hEx84/show/)

查看更多
登录 后发表回答