diff --git a/lib/decorators/autobound.js b/lib/decorators/autobound.js new file mode 100644 index 0000000..c0caee7 --- /dev/null +++ b/lib/decorators/autobound.js @@ -0,0 +1,33 @@ +'use strict'; + +exports.__esModule = true; +exports['default'] = autobound; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +var _tcomb = require('tcomb'); + +var _tcomb2 = _interopRequireDefault(_tcomb); + +function autobound(target, key, descriptor) { + var value = descriptor.value; + + if (process.env.NODE_ENV !== 'production') { + _tcomb2['default'].assert(_tcomb2['default'].Func.is(value), '@autobound decorator can only be applied to methods'); + } + + return { + configurable: true, + get: function get() { + var boundValue = value.bind(this); + Object.defineProperty(this, key, { + value: boundValue, + configurable: true, + writable: true + }); + return boundValue; + } + }; +} + +module.exports = exports['default']; \ No newline at end of file diff --git a/lib/index.js b/lib/index.js index c1bda23..711e1ea 100644 --- a/lib/index.js +++ b/lib/index.js @@ -68,4 +68,10 @@ var _decoratorsSkinnable = require('./decorators/skinnable'); var _decoratorsSkinnable2 = _interopRequireDefault(_decoratorsSkinnable); -exports.skinnable = _decoratorsSkinnable2['default']; \ No newline at end of file +exports.skinnable = _decoratorsSkinnable2['default']; + +var _decoratorsAutobound = require('./decorators/autobound'); + +var _decoratorsAutobound2 = _interopRequireDefault(_decoratorsAutobound); + +exports.autobound = _decoratorsAutobound2['default']; \ No newline at end of file diff --git a/src/decorators/autobound.js b/src/decorators/autobound.js new file mode 100644 index 0000000..82537d4 --- /dev/null +++ b/src/decorators/autobound.js @@ -0,0 +1,23 @@ +import t from 'tcomb'; + +export default function autobound(target, key, descriptor) { + const { value } = descriptor; + + if (process.env.NODE_ENV !== 'production') { + t.assert(t.Func.is(value), `@autobound decorator can only be applied to methods`); + } + + return { + configurable: true, + get() { + const boundValue = value.bind(this); + Object.defineProperty(this, key, { + value: boundValue, + configurable: true, + writable: true + }); + return boundValue; + } + }; +} + diff --git a/src/index.js b/src/index.js index bf01db0..c73e6e8 100644 --- a/src/index.js +++ b/src/index.js @@ -9,3 +9,4 @@ export props from './decorators/props'; export pure from './decorators/pure'; export queries from './decorators/queries'; export skinnable from './decorators/skinnable'; +export autobound from './decorators/autobound';