Last Updated: February 25, 2016
·
6.763K
· david morrow

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

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside