将模型的属性呈现为 HTML 页面标题

Render an attribute of a model as the HTML page title

本文关键字:HTML 标题 模型 属性      更新时间:2023-09-26

如何将User模型的fullName呈现为 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

更新

我认为使用 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'));
  }
});

现场演示 http://emberjs.jsbin.com/ExAkulA/5/edit