[英]Render an attribute of a model as the HTML page title
我怎样才能使fullName
中的User
模型为HTML页面标题,而不是...
在"Details for ..."
?
App.User = DS.Model.extend({
firstName : DS.attr('string'),
lastName : DS.attr('string'),
fullName: function() {
return this.get('firstName') + ' ' + this.get('lastName');
}.property('firstName', 'lastName'),
});
App.UserRoute = Em.Route.extend({
model: function(params){
return this.store.find('user', params.user_id);
},
activate: function() {
$(document).attr('title', 'Details for ...');
}
});
您可以在UserController
观察fullName
属性,并在属性更改时更新标题:
App.UserController = Ember.ObjectController.extend({
updateTitle: function() {
$(document).attr('title', 'Details for ' + this.get('fullName'));
}.observes('fullName')
})
只需设置一次标题,而无需绑定,则可以使用以下内容:
App.UserRoute = Em.Route.extend({
originalTitle: null,
model: function(params){
return this.store.find('user', params.user_id);
},
activate: function() {
// save the original title
this.set('originalTitle', $(document).attr('title'));
// we use Ember.run.next because the currentModel property isn't avaliable
Ember.run.next(this, function() {
// the resolved result from model method, is set in the currentModel property
$(document).attr('title', 'Details for ' + this.currentModel.get('fullName'));
});
},
deactivate: function() {
// restore the original title
$(document).attr('title', this.get('originalTitle'));
}
});
这是jsbin http://emberjs.jsbin.com/ExAkulA/3/edit
UPDATE
我认为使用afterModel
而不是activate
方法是实现它的更好方法:
App.UserRoute = Em.Route.extend({
originalTitle: null,
model: function(params){
return this.store.find('user', params.user_id);
},
afterModel: function(model) {
// save the original title
this.set('originalTitle', $(document).attr('title'));
// no hacks here, we have the resolved model avaliable
$(document).attr('title', 'Details for ' + model.get('fullName'));
},
deactivate: function() {
// restore the original title
$(document).attr('title', this.get('originalTitle'));
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.