index.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. /**
  2. * Expose `Delegator`.
  3. */
  4. module.exports = Delegator;
  5. /**
  6. * Initialize a delegator.
  7. *
  8. * @param {Object} proto
  9. * @param {String} target
  10. * @api public
  11. */
  12. function Delegator(proto, target) {
  13. if (!(this instanceof Delegator)) return new Delegator(proto, target);
  14. this.proto = proto;
  15. this.target = target;
  16. this.methods = [];
  17. this.getters = [];
  18. this.setters = [];
  19. this.fluents = [];
  20. }
  21. /**
  22. * Delegate method `name`.
  23. *
  24. * @param {String} name
  25. * @return {Delegator} self
  26. * @api public
  27. */
  28. Delegator.prototype.method = function(name){
  29. var proto = this.proto;
  30. var target = this.target;
  31. this.methods.push(name);
  32. proto[name] = function(){
  33. return this[target][name].apply(this[target], arguments);
  34. };
  35. return this;
  36. };
  37. /**
  38. * Delegator accessor `name`.
  39. *
  40. * @param {String} name
  41. * @return {Delegator} self
  42. * @api public
  43. */
  44. Delegator.prototype.access = function(name){
  45. return this.getter(name).setter(name);
  46. };
  47. /**
  48. * Delegator getter `name`.
  49. *
  50. * @param {String} name
  51. * @return {Delegator} self
  52. * @api public
  53. */
  54. Delegator.prototype.getter = function(name){
  55. var proto = this.proto;
  56. var target = this.target;
  57. this.getters.push(name);
  58. proto.__defineGetter__(name, function(){
  59. return this[target][name];
  60. });
  61. return this;
  62. };
  63. /**
  64. * Delegator setter `name`.
  65. *
  66. * @param {String} name
  67. * @return {Delegator} self
  68. * @api public
  69. */
  70. Delegator.prototype.setter = function(name){
  71. var proto = this.proto;
  72. var target = this.target;
  73. this.setters.push(name);
  74. proto.__defineSetter__(name, function(val){
  75. return this[target][name] = val;
  76. });
  77. return this;
  78. };
  79. /**
  80. * Delegator fluent accessor
  81. *
  82. * @param {String} name
  83. * @return {Delegator} self
  84. * @api public
  85. */
  86. Delegator.prototype.fluent = function (name) {
  87. var proto = this.proto;
  88. var target = this.target;
  89. this.fluents.push(name);
  90. proto[name] = function(val){
  91. if ('undefined' != typeof val) {
  92. this[target][name] = val;
  93. return this;
  94. } else {
  95. return this[target][name];
  96. }
  97. };
  98. return this;
  99. };