简体   繁体   中英

Class and Object confusion within Ember.js

This is a very basic question but I'm a little bit confounded. My understanding is that convention dictates that class definitions are capitalised but object instances are not. So when I do the following:

App = require("app");
module.exports = App.AuthManager = Ember.Object.extend({
  apiKey: null,

  // Load the current user if the cookies exist and is valid
  init: function() {
    this._super();
    var accessToken = $.cookie('access_token');
    var authUserId  = $.cookie('auth_user');
    if (!Ember.isEmpty(accessToken) && !Ember.isEmpty(authUserId)) {
        this.authenticate(accessToken, authUserId);
    }
  },

  // ... 
}

I assume I am only defining the AuthManager's class definition. Then if I do this:

module.exports = App.ApplicationRoute = Ember.Route.extend({
    init: function() {
        this._super(); 
        App.AuthManager = App.AuthManager.create(); 
    }
});

My understanding is that App.AuthManager = App.AuthManager.create(); instantiates the instance and that the ApplicationRouter is pretty much the first thing that is executed in an ember app. Is that right? If so, shouldn't convention dictate that the instance be called authManager ? Also, is it typical to put the class definition into the same namespace as the object? I suspect this may come down to my relatively shallow understanding of JS but any help would be appreciated.

If so, shouldn't convention dictate that the instance be called authManager?

Yes indeed, this line:

 App.AuthManager = App.AuthManager.create();

should read, mostly to avoid confusion (although it's a singleton and singletons could also be capitalized)

 App.authManager = App.AuthManager.create(); 

since your are creating an instance of the App.AuthManager class definition, this is at least how ember dictates it.

Also, is it typical to put the class definition into the same namespace as the object

I guess not, (however Javascript let's you do all sort of things) therefore the lowercase naming of an Object instance, rather then a Capitalized like a class definition. So later on you could create more instances of the same class like:

App.foo = App.AuthManager.create();
App.bar = App.AuthManager.create();

(obviously this doesn't make much sense for a class that is meant to be a singleton, but you get the point)

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM