mayor-app-container
Version:
mayor-app-container
124 lines (99 loc) • 3.23 kB
JavaScript
;
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Container = (function () {
function Container() {
_classCallCheck(this, Container);
this.bindings = {};
this.instances = {};
}
/**
* Register a binding with given closure.
*
* @public
* @param {String} key - binding name
* @param {Function} closure - to be resolved closure
* @param {Boolean=} shared = false - if yes given closure will be resolved only once
*/
_createClass(Container, [{
key: "bind",
value: function bind(key, closure) {
var shared = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
var binding = { closure: closure, shared: shared };
this.bindings[key] = binding;
}
/**
* Register a binding if it's not bound yet.
*
* @public
* @param {String} key
* @param {Array} ...args
*/
}, {
key: "bindIf",
value: function bindIf(key) {
if (this.bindings[key]) {
return;
}
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
this.bind.apply(this, [key].concat(args));
}
/**
* Register a shared binding.
*
* @public
* @param {String} key
* @param {Function} closure
*/
}, {
key: "singleton",
value: function singleton(key, closure) {
this.bind(key, closure, true);
}
/**
* Register an existing instance as shared binding.
*
* @public
* @param {String} key
* @param {Object} instance
*/
}, {
key: "instance",
value: function instance(key, _instance) {
var closure = function closure() {
return _instance;
};
this.bind(key, closure, true);
}
/**
* Resolve given key.
*
* @public
* @param {string} key
* @return {Object}
*/
}, {
key: "make",
value: function make(key) {
// there is already registered instance return that.
if (this.instances.hasOwnProperty(key)) {
return this.instances[key];
}
var _bindings$key = this.bindings[key];
var closure = _bindings$key.closure;
var shared = _bindings$key.shared;
var result = closure.call(null, this);
if (shared) {
this.instance(key, result);
}
return result;
}
}]);
return Container;
})();
exports.default = Container;