0.3.1 • Published 10 years ago

singleton.js v0.3.1

Weekly downloads
3
License
MIT
Repository
github
Last release
10 years ago

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()  // => true
new Modal() instanceof Modal // => true
function Modal(priority){
  this.priority = priority;
}
Modal.prototype.open  = function() { /****/ };
Modal.prototype.close = function() { /****/ };

// Create a singleton from an existing function constructor
var Alert = singleton(Modal);
new Alert(10);
new Alert() === new Alert()  // => true
// `new` is optional
Alert() === new Alert()      // => true
new Alert() instanceof Alert // => true
new Alert() instanceof Modal // => true
new Alert().priority         // => 10
new Alert(3).priority        // => 10
// Define singleton's constructor
var Printer = singleton(function(name) {
  this.name  = name;
  this.queue = [];
});
Printer.prototype.print = function() { /****/ };

new Printer('Office Printer');
new Printer().name        // => 'Office Printer'
new Printer('Chuck').name // => 'Office Printer'

Example with Backbone.js Collections

var Movie = Backbone.Model.extend();

var Movies = singleton(Backbone.Collection.extend({
  model: Movie
}));

// Alternatively
// var Movies = singleton(Backbone.Collection);
// Movies.prototype.model = Movie;

new Movies() === new Movies() // => true

new Movies().add([
  {id: 100, title: 'Gattica'},
  {id: 101, title: 'Batman Begins'}
]);

new Movies().length // => 2

// Static/Own properties are maintained
var BMovies = Movies.extend();
new BMovies() instanceof Movies              // => true
new BMovies() instanceof Backbone.Collection // => true
0.3.1

10 years ago

0.3.0

10 years ago

0.2.0

11 years ago

0.1.0

11 years ago