1
votes

I am using the latest Ember, 2.1, and am wondering how to set some application wide variables, such as user id, username, email, etc, presumably on the application controller.

While ember applications have tons of files, I haven't really done a lot yet, I'm somewhat confident I'm sharing just the right code. I don't have a login route file. I have the ember simple auth plugin installed, but I'm not actually using/invoking it any special way, except for mixing it into my application route:

import ApplicationRouteMixin from 'simple-auth/mixins/application-route-mixin';
export default Ember.Route.extend(ApplicationRouteMixin)

My router:

this.route('login')

My login template:

<button {{action 'forceLogin'}}>Force login of [email protected] by clicking this action button</button>
<p>Your account id is: {{account_id}}</p>

My login controller:

export default Ember.Controller.extend({
  actions: {
    forceLogin: () => {
      var data = {
        "account_id": 123,
        "email":"[email protected]",
        "name":"Devin Rhode"
      }
      this.setProperties(data)
    }
  }
});

I have the forceLogin controller action being called, but, the {{account_id}} is not populating into the template. How could I get the account_id to render back into the template? How could I make the account_id globally accessible to my ember application by calling this.get('account_id') wherever I need it?

Currently I get the error:

 Cannot read property 'setProperties' of undefined
1

1 Answers

2
votes

You get the error because of the way you define forceLogin. Arrow functions are bound to the context where they're defined. Here's what your code compiles to:

var _this = this; // we capture `this` from out here!
export default Ember.Controller.extend({
  actions: {
    forceLogin() {
      ...
      _this.setProperties(data) // `_this` is the window!
    }
  }
});

That's no good because this should be the instance of the controller and instead it's the window.

Instead you should define forceLogin like this:

export default Ember.Controller.extend({
  actions: {
    forceLogin() {
      ...
      this.setProperties(data) // `this` is our controller instance
    }
  }
});

To get the account_id from somewhere else, you can inject the login controller:

// in some other controller
export default Ember.Controller.extend({
  login: Ember.inject.controller(),

  actions: {
    doSomethingWithTheAccountId() {
      var accountId = this.get('login.account_id');
      ...
    }
  }
});

It would be cleaner to move those properties to a service, which you can inject anywhere with Ember.inject.service()