Decorate any Javascript object with a convenient builder, which returns an immutable object
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
src
test
.eslintrc.js
.gitattributes
.gitignore
.travis.yml
Gruntfile.js
LICENSE
README.md
builder-decorator.min.js
example.html
main.js
package.json

README.md

js-builder-decorator

Decorate any Javascript object with a convenient builder, which returns an immutable object with getters.

Build Status npm version npm version

Standard usage:

var StudentClass = function(){
  this.name = "Some default name";
  this.age = undefined;
  this.address = {};
  this.prettyName = function(){};
};
var StudentClassBuilder = BuilderDecorator(StudentClass);

var student = StudentClassBuilder()
  .name("John")
  .age(17)
  .address({postcode: "90210"})
  .prettyName(function(){ return "Hi, I'm " + this.name() + "!"; })
  .build();

student.name();       // "John"
student.age();        // 17
student.address();    // {postcode: "90210"}
student.prettyName(); // function(){ return "Hi, I'm " + this.name() + "!"; }

Requiring in Node:

var BuilderDecorator = require('js-builder-decorator').BuilderDecorator;

Locking functions after build

var StudentClassBuilderLocked = BuilderDecorator(StudentClass, {lockFunctionsAfterBuild: true});
var student = StudentClassBuilderLocked()
  .name("John")
  .prettyName(function(){ return "Hi, I'm " + this.name() + "!"; })
  .build();

student.name();       // "John"
student.prettyName(); // "Hi, I'm John!"

Enforcing no null fields

// Throwing exception if any field isn't set
var StudentClassBuilderNoNulls = BuilderDecorator(StudentClass, {allFieldsMustBeSet: true});

try {
  var student = StudentClassBuilderNoNulls().build(); // This throws an exception
} catch (E) {
  console.log(E); // The following fields were not set: name,age,address,prettyName
}

Installation

If you have Node.js installed, run npm install js-builder-decorator in your project directory.
Else, you can download the latest version from Github here.