Build chainable fluent interfaces the easy way in node.js.
With this meta-module you can write modules with chainable interfaces.
Chainsaw takes care of all of the boring details and makes nested flow control
super simple too.
Just call Chainsaw with a constructor function like in the examples below.
In your methods, just do saw.next() to move along to the next event and
saw.nest() to create a nested chain.
Examples
add_do.js
This silly example adds values with a chainsaw.
var Chainsaw = require('chainsaw');function AddDo (sum) { return Chainsaw(function (saw) { this.add = function (n) { sum += n; saw.next(); }; this.do = function (cb) { saw.nest(cb, sum); }; });}AddDo(0) .add(5) .add(10) .do(function (sum) { if (sum > 12) this.add(-10); }) .do(function (sum) { console.log('Sum: ' + sum); });
Output:
Sum: 5
prompt.js
This example provides a wrapper on top of stdin with the help of
node-lazy for line-processing.
var Chainsaw = require('chainsaw');var Lazy = require('lazy');module.exports = Prompt;function Prompt (stream) { var waiting = []; var lines = []; var lazy = Lazy(stream).lines.map(String) .forEach(function (line) { if (waiting.length) { var w = waiting.shift(); w(line); } else lines.push(line); }) ; var vars = {}; return Chainsaw(function (saw) { this.getline = function (f) { var g = function (line) { saw.nest(f, line, vars); }; if (lines.length) g(lines.shift()); else waiting.push(g); }; this.do = function (cb) { saw.nest(cb, vars); }; });}