function chart(){var width = 720; // default widthfunction my() {// generate chart here, using `width`}my.width = function(value){if (!arguments.length) return width;width = value;return my;};}
function plotter(){makeAccessors(["width","height","css"]);go._height = 42; // set a defaultreturn go;
function go(selection){console.log(go._width,go._height,go._css);}
function makeAccessors(names){names.forEach(function(n){go[n]=function(v){return arguments.length ? (go["_"+n]=v,this) : go["_"+n];};});}}// Spoof a D3 selectionvar selection = {call:function(f){ f.call(this,this); return this; }};var p1 = plotter().width(17);var p2 = plotter().height(99).css(function(){}); // Yay method chaining!selection.call(p1); // Yay default values!//-> 17 42 undefinedselection.call(p2); // Overridden and complex values!//-> undefined 99 function (){}selection.call(p1); // Yay preserving values!//-> 17 42 undefined
function plotter(){var opts={};
makeAccessors(["width","height","css"]);
opts.height = 42; // set a defaultreturn go;function go(selection){console.log(opts.width,opts.height,opts.css);}function makeAccessors(names){names.forEach(function(n){go[n]=function(v){ return arguments.length?(opts[n]=v,this):opts[n]; };});}}
function plotter(){var opts={ // enumerate all user-settable values and defaultswidth : null,height : 42,css : null};makeAccessors();return go;
function go(selection){
// your real plotting code here
console.log(opts.width,opts.height,opts.css);}function makeAccessors(){for (var n in opts){if (!opts.hasOwnProperty(n)) continue;
> One more variation/improvement: if you enumerate ...
sweet!
-r
--
http://www.cfcl.com/rdm Rich Morin
http://www.cfcl.com/rdm/resume r...@cfcl.com
http://www.cfcl.com/rdm/weblog +1 650-873-7841
Software system design, development, and documentation
function property(value) {
return function(_) {
if (!arguments.length) return value;
value = _;
return chart;
};
}
Then, you can define properties like so:
chart.foo = property(42);
chart.bar = property(true);
And you can access them to render the chart like so:
var foo = chart.foo(),
bar = chart.bar();
Mike
function property(value) {
return function(_) {
if (!arguments.length) return value;
value = _;
return this;
};
}
Mike
Consider this approach:function property(value) {
return function(_) {
if (!arguments.length) return value;
value = _;
return chart;
};
}Then, you can define properties like so:
chart.foo = property(42);
chart.bar = property(true);
And you can access them to render the chart like so:
var foo = chart.foo(),
bar = chart.bar();
function makeAccessors(){for (var n in opts){if (!opts.hasOwnProperty(n)) continue;go[n]=function(v){ return arguments.length?(opts[n]=v,this):opts[n]; };}}
function createAccessors(){
for (var n in opts){if (!opts.hasOwnProperty(n)) continue;
plot[n] = (function(n){ return function(v){return arguments.length ? (opts[n]=v,this) : opts[n];}})(n);}}