1

I have the need to do something like this:

<script src="apiWrapper.js"></script>
<script>
  apiWrapper.init('api_key');
  apiWrapper.doSomethingElse();
</script>

Essentially, have a singleton style object in a page that I can add methods and properties too and have available from anywhere within the page.

What's the best way to do this?

Neil Middleton
  • 22,105
  • 18
  • 80
  • 134
  • possible duplicate of [Simplest/Cleanest way to implement singleton in JavaScript?](http://stackoverflow.com/questions/1479319/simplest-cleanest-way-to-implement-singleton-in-javascript) – Alex K. Jul 31 '13 at 12:54
  • For patterns like that it can be a pain if you have to check for the init state in subsequent calls, so personally I prefer `var myApi = ApiWrapper.init(apikey);` – Alex K. Jul 31 '13 at 12:57
  • Is it possible you're overthinking the singleton idea. Can't you just declare a global object that contains the properties you need? – Splendiferous Jul 31 '13 at 13:02

3 Answers3

3

You could use this approach (which gives you a way of having private properties/functions):

var apiWrapper = apiWrapper || (function () {

  /* private functions here */
  var privateFunction = function () {
  }

  /* public functions here */
  return {
    init: function (opts) {},
    doSomethingElse: function () {}
  };
})();
kamituel
  • 34,606
  • 6
  • 81
  • 98
1

I use this structure for my scripts too:

apiWrapper.js:

var apiWrapper = apiWrapper || {};

apiWrapper = {
    doSomethingElse: function() {

    },
    init: function(options) {

    }
};

If you want to do function chaining (like jQuery), simply return this; at the end of the functions you wish to chain.

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
0
<script>
...
    // create your singleton in the global scope
    if(!("apiWrapper" in window))
        window.apiWrapper = {};
    ...
    // use your singleton object
    apiWrapper.init = function() {...};
    apiWrapper.prop = 123;
    ...
    apiWrapper.init();
</script>
Louis Ricci
  • 20,804
  • 5
  • 48
  • 62