Skip to content

Instantly share code, notes, and snippets.

@didxga
Last active November 23, 2016 10:49
Show Gist options
  • Save didxga/8f0bf6ba05c8011112978d99932e8c20 to your computer and use it in GitHub Desktop.
Save didxga/8f0bf6ba05c8011112978d99932e8c20 to your computer and use it in GitHub Desktop.
Different Backbone Singleton Implementations
//code quote from http://blog.robertpataki.com/blog/2015/08/04/using-the-singleton-pattern-in-requirejs/
define([],
function() {
'use strict';
var instance = null;
function Singie() {
if(!!!instance){
this.initialize();
instance = this;
}
window.SINGIE = instance; // Good to have reference on window
return instance;
};
Singie.prototype = {
initialize: function() {
// Private vars
this._hello = 'Hello';
// Public methods
this.sayHello = function sayHello(name) {
var n = name || 'Anonymous';
console.log(this._hello + ' ' + n);
}
}
};
return Singie;
}
);
var singie = new Singie();
singie.sayHello('Foo');
// Will put 'Hello Foo' in the console
var singie = new Singie();
var singieClone = new Singie();
console.log(singie === singieClone);
// Will put true in the console
var singie = new Singie();
SINGIE.sayHello('Bar');
// Will put 'Hello Bar' in the console
define(function(){
var instance = null;
function MySingleton(){
if(instance !== null){
throw new Error("Cannot instantiate more than one MySingleton, use MySingleton.getInstance()");
}
this.initialize();
}
MySingleton.prototype = {
initialize: function(){
// summary:
// Initializes the singleton.
this.foo = 0;
this.bar = 1;
}
};
MySingleton.getInstance = function(){
// summary:
// Gets an instance of the singleton. It is better to use
if(instance === null){
instance = new MySingleton();
}
return instance;
};
return MySingleton.getInstance();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment