1

如何fullNameUser模型的 呈现为 HTML 页面标题而不是...in "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 ...');
  }
});
4

1 回答 1

1

您可以观察 中的fullName属性UserController,并在属性更改时更新标题:

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

于 2013-11-08T17:51:26.097 回答