Ember.js current_user - accessing global variable from controller

点点圈 提交于 2019-11-30 05:49:43

In our app we do it same as @MilkyWayJoe suggested, but I think your approach is really interesting. Passing current_user thru JSON is a really elegant approach.

I've not experimented too much, but from what I can tell in your example the problem is nothing to do with the serializer. It's a problem with the computed property - you need to specify that it depends on App.metaData.current_user.

App.ApplicationController = Ember.Controller.extend({
  currentUser: function() {
    return Ember.get('App.metaData.current_user')
  }.property('App.metaData.current_user')
});

This tells ember that it should re-calculate the currentUser property whenever App.metaData.currentUser changes. Otherwise it will run the fx once (before your ajax returns) and cache the response.

You can define a variable to represent the user id in a script tag. This should be done in the server template:

<script type="text/javascript">
    window.user_id = 1;
</script>

Then in your app, you can define a property in the ApplicationController which will store the current user model, and then you can find with the user_id variable:

window.App = Ember.Application.create();

App.store = DS.Store.create({
    revision: 12
});

App.User = DS.Model.extend({
    firstName: DS.attr('string'),
    lastName: DS.attr('string'),
    fullName: function() {
        return '%@ %@'.fmt(
            this.get('firstName'),
            this.get('lastName')
        );
    }.property('firstName', 'lastName')
});

App.ApplicationController = Em.Controller.extend({
    userInfo: null,
    init: function() {
        // this will fire a GET request to users_controller 
        this.set('userInfo', App.User.find(window.user_id));
    }
});

Then your template, you can use the properties in ApplicationController#userInfo.

<script type="text/x-handlebars">
    <h1>App</h1>
    {{userInfo.fullName}}
</script>

If you need to use this data from a route, you can use controllerFor, or if you need to access from another controller, you can use needs.

(see fiddle)

Just keep in mind this might not be the best solution for all scenarios as it adds one more request to your app initialization, but it does the trick for me right now.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!