Last Updated: February 25, 2016
·
6.074K
· dperrymorrow

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