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
Written by David Morrow
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Backbone.js
Authors
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
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#