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
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#