i-sn3w
Last Updated: February 25, 2016
·
5.197K
· dperrymorrow
37b092a324da25d53fd63d780692b174

Backbone.js singleton example

Ever wanna have a backbone singleton class? Allowing you to access a classes instance from anywhere without having to pass around a handle to an instance.

The additional backbone class

Backbone.Singleton = {
  getInstance: function () {
    if (this._instance === undefined) {
      this._instance = new this();
    }
    return this._instance;
  }
}

Example usage with a Backbone.Router

TestRouter = function(){};
_.extend( TestRouter, Backbone.Router );
// extend Backbone.Singleton
_.extend( TestRouter, Backbone.Singleton );
// access your router from anywhere!!
// just make sure not to call new, 
// only use .getInstance()
var inst = TestRouter.getInstance();

I have a fork of Backbone.js with this code addition and tests on github. https://github.com/dperrymorrow/backbone

Say Thanks
Respond