1
0

property-accessors.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. (function() {
  2. var Mixin, PropertyAccessors, WeakMap, _ref, _ref1,
  3. __hasProp = {}.hasOwnProperty,
  4. __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
  5. Mixin = require('mixto');
  6. WeakMap = (_ref = global.WeakMap) != null ? _ref : require('es6-weak-map');
  7. module.exports = PropertyAccessors = (function(_super) {
  8. __extends(PropertyAccessors, _super);
  9. function PropertyAccessors() {
  10. _ref1 = PropertyAccessors.__super__.constructor.apply(this, arguments);
  11. return _ref1;
  12. }
  13. PropertyAccessors.prototype.accessor = function(name, definition) {
  14. if (typeof definition === 'function') {
  15. definition = {
  16. get: definition
  17. };
  18. }
  19. return Object.defineProperty(this, name, definition);
  20. };
  21. PropertyAccessors.prototype.advisedAccessor = function(name, definition) {
  22. var getAdvice, setAdvice, values;
  23. if (typeof definition === 'function') {
  24. getAdvice = definition;
  25. } else {
  26. getAdvice = definition.get;
  27. setAdvice = definition.set;
  28. }
  29. values = new WeakMap;
  30. return this.accessor(name, {
  31. get: function() {
  32. if (getAdvice != null) {
  33. getAdvice.call(this);
  34. }
  35. return values.get(this);
  36. },
  37. set: function(newValue) {
  38. if (setAdvice != null) {
  39. setAdvice.call(this, newValue, values.get(this));
  40. }
  41. return values.set(this, newValue);
  42. }
  43. });
  44. };
  45. PropertyAccessors.prototype.lazyAccessor = function(name, definition) {
  46. var values;
  47. values = new WeakMap;
  48. return this.accessor(name, {
  49. get: function() {
  50. if (values.has(this)) {
  51. return values.get(this);
  52. } else {
  53. values.set(this, definition.call(this));
  54. return values.get(this);
  55. }
  56. },
  57. set: function(value) {
  58. return values.set(this, value);
  59. }
  60. });
  61. };
  62. return PropertyAccessors;
  63. })(Mixin);
  64. }).call(this);