Singleton.js
JavaScript Singletons made easy.
Installation
$ npm install singleton.js
var singleton = require('singleton.js');
Browser
ES5 browser (>= IE9) required.
singleton.js
singleton.min.js
API
singleton(Ctor)
arguments
Ctor
Optional. Function constructor.
returns
- Singleton function constructor.
- Returns initial instance for all subsequent instantiations.
new
is optional.- Inherits from passed function constructor.
- Will have own properties of passed function constructor.
var Modal = singleton();
Modal.prototype = {
open: function() { },
close: function() { }
};
new Modal() === new Modal()
new Modal() instanceof Modal
function Modal(priority){
this.priority = priority;
}
Modal.prototype.open = function() { };
Modal.prototype.close = function() { };
var Alert = singleton(Modal);
new Alert(10);
new Alert() === new Alert()
Alert() === new Alert()
new Alert() instanceof Alert
new Alert() instanceof Modal
new Alert().priority
new Alert(3).priority
var Printer = singleton(function(name) {
this.name = name;
this.queue = [];
});
Printer.prototype.print = function() { };
new Printer('Office Printer');
new Printer().name
new Printer('Chuck').name
Example with Backbone.js Collections
var Movie = Backbone.Model.extend();
var Movies = singleton(Backbone.Collection.extend({
model: Movie
}));
new Movies() === new Movies()
new Movies().add([
{id: 100, title: 'Gattica'},
{id: 101, title: 'Batman Begins'}
]);
new Movies().length
var BMovies = Movies.extend();
new BMovies() instanceof Movies
new BMovies() instanceof Backbone.Collection