1

I'm trying to fetch the current logged in user via my REST API and then set it as a property of the ApplicationController. This is how I'm trying to do it:

App.ApplicationController = Ember.Controller.extend({
    init: function() {
        this._super();
        var self = this;
        App.User.findCurrent().then(function(user) {
          self.set('currentUser', user);
        });
    }
});

App.User = Ember.Object.extend({});

App.User.reopenClass({
    findCurrent: function() {
        return $.getJSON('/api/v1/users/current').then(
            function(response) {
                return response.user;
            }
        );
    }
});

When I check the Chrome network tab, I see there's a call to the API and the JSON is returned, but when I try to access e.g. {{currentUser.name}} in my application template (or a partial of it), it doesn't return the name. No errors are given as well.

But in the application template it doesn't return it.

What am I missing?

Thanks!

Edit

When I create another controller, e.g. HelpController and visit /help, then {{currentUser.name}} does return the username:

App.HelpController = Ember.Controller.extend({
    needs: ['application'],
    currentUser: Ember.computed.alias('controllers.application.currentUser')
});

Edit 2

Sorry, I forgot to mention that I'm actually trying to use {{currentUser.name}} from a partial ({{partial 'sidebar'}}), but that shouldn't change anything, because that's the same scope, right?

Edit 3

I noticed something very strange. When I call {{currentUser.name}} in my application template (which is not what I want btw), then it also works in the {{partial 'sidebar'}}.

Edit 4

As per request:

DEBUG: Ember.VERSION : 1.0.0-rc.6 ember.js?body=1:361
DEBUG: Handlebars.VERSION : 1.0.0-rc.4 ember.js?body=1:361
DEBUG: jQuery.VERSION : 1.10.0
4

1 に答える 1

1

これは、このロジックを配置する正しい場所ではありません。これを簡単に行うには、ルート フックmodelとを使用できます。一般に、データの残りの読み込みはルートフックで行われます。これにより、ロード中にルーターを一時停止できるため、コントローラーとテンプレートが機能するまでに、ロードされたデータを処理しています。afterModelApplicationRoute

App.ApplicationRoute = function() {
  model: function() {
    return App.User.findCurrent();
  },
  afterModel: function(model) {
    App.set('currentUser', model)
  }
}
于 2013-07-27T05:54:51.510 に答える