Helping designing a javascript class that exposes properties that I initialize

67 views Asked by At

I want to initialize my javascript class like this:

Example.init({"settings": {"baseUrl":"http://example.com"}, "user": {"id":123, "name":"john doe"} );

And then I want to be able to use it like this:

Example.settings.baseUrl
Example.user.id;
Example.user.name;

I am currently using the module pattern like this:

Example = (function(){

       var _init = function(data) {

       };

       return {
           init: function($data) {
              _init($data);
           }
       };
})();

Example.module2 = (function(){

       var _init = function(data) {
          if(Example.user.id > 0) {    // referencing data set in the Example.init

          }
       };

       return {
           init: function($data) {
              _init($data);
           }
       };
})();

I'm not sure how I can expose these properties, looking for an explanation and guidance.

(please comment on best practise also, should I use $ for parameters and if so when?)

Note: Here is basic outline of what I am trying to do.

  1. The first thing I will do is call the Example.init function in all my pages:

    Example.init({"settings": {"baseUrl":"http://example.com"}, "user": {"id":123, "name":"john doe"} );

  2. I want my other modules to be able to reference this data I set in the .init() method, see the Example.module2 I added above.

Is there a timing issue with this?

1

There are 1 answers

4
ratiorick On
Example = (function(){

    var _init = function(data){
        // manually 
        //this.settings = data.settings || NULL;
        //this.user = data.user || NULL ;
        for (prop in data){
            this[prop] = data[prop];
        }
    }

    return {
           init: function(data) {
               _init.call(this, data); 
           }
       };
})();
Example.init(
    {"settings": {"baseUrl":"http://example.com"}, "user": {"id":123, "name":"john doe"}});

console.log(Example.settings.baseUrl); 
console.log(Example.user.id);
console.log(Example.user.name);

As for your other question "using $ in variable names " - It is a comment naming convention when the variable contains a Jquery object -