设置页面标题的最佳方法是什么,以便在URL之间转换时,标题将反映新的状态?有没有办法设置路由器这样做?
我想要一个允许我为每个状态设置页面标题架构的方法.因此,如果路由有参数,它们将被传递到pageTitle:
sessions : Ember.Route.extend({
route:"/sessions",
connectOutlets : function(router) {
//...
},
pageTitle:function(){
return "Sessions";
},
})
Run Code Online (Sandbox Code Playgroud)
我对如何在模型或其他地方实现此类功能最好的建议持开放态度.
Mil*_*Joe 19
之前的答案适用于旧版本的Ember.经过多次更改后,Framework已达到版本1.0 RC2并且它已接近最终版本,因此我决定更新此答案.
作为一个例子,请查看这个小提琴中定义的路线:http://jsfiddle.net/schawaska/dWcUp/
这个想法与之前的答案相同,只是以不同的方式,因为路由API已经发生了很大的变化.
下面的路线使用 activate钩子通过jQuery设置文档的标题:
App.ProductRoute = Em.Route.extend({
activate: function() {
$(document).attr('title', 'Auto Web Shop - Product');
}
});
Run Code Online (Sandbox Code Playgroud)
编辑:如评论部分所述:
FYI activate是API方法,而不是输入 - pauldechov
这个答案是在以前版本的Ember中给出的,不再适用.
在你的内部connectOutlets你可以做一些简单的事情,如使用jQuery来修改文档title属性:
[...]
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');
}
}),
[...]
Run Code Online (Sandbox Code Playgroud)
但是你必须为每条路线做这件事.
如果您有类似导航栏控制器的设置选定的导航菜单项,您可以观看 selected属性以将"活动"或"选定"css类绑定到导航项并设置页面标题; 或者你可以为navitem模型上的标题提供一个属性,你可以通过上下文(但我相信你必须在视图中处理这个并从那里过渡到路线).
无论如何,这只是为了展示设置页面标题的可能方法之一.
编辑:我已经修改了现有的小提琴来做到这一点.看看navigateTo路由器中的方法:http://jsfiddle.net/schawaska/hEx84/(看它运行到这里http://jsfiddle.net/schawaska/hEx84/show/)
当我努力想出一个很好的模式来设置页面标题时,使用最新的Ember.js(1.0.0 RC7),我决定创建一个子类Ember.Route:
AppRoute = Ember.Route.extend({
renderTemplate: function(controller, model) {
this.render();
var pageTitle = this.title ? this.title(controller, model) : null;
document.title = pageTitle ? pageTitle : "Default Title";
}
});
// all routes extend this new 'AppRoute'
App.PageRoute = AppRoute.extend({
model: function(params) {
// return your model
return App.Page.find(params.page_id);
},
title: function(controller, model) {
// return whatever should be your page title
return controller.get('title');
},
});
Run Code Online (Sandbox Code Playgroud)
如果这个拉取请求被合并,这可能会由Ember.js原生支持:路由器现在观察路由处理程序上的'title'属性并设置document.title.注意:此拉取请求似乎没有通过controller并model作为参数.
如果您更喜欢Coffee Script等价物:Ember.js:一种简单而干净的方式来设置页面标题.
我采用了这种方法:
Ember.Route.reopen({
enter: function(router) {
this._super(router)
# Set page title
name = this.parentState.get('name')
if (!Em.none(name)) {
capitalizedName = name.charAt(0).toUpperCase() + name.slice(1)
$(document).attr('title', "Website - " + capitalizedName)
}
}
})
Run Code Online (Sandbox Code Playgroud)
使用navigateTo出现了一些问题,至少对我的情况来说,这更加可靠和清洁.