fv-store
Version:
Fast and simple key = value storage
85 lines (67 loc) • 2.83 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var SUBSCRIPTIONS = {};
var Subscription = function () {
function Subscription() {
_classCallCheck(this, Subscription);
}
_createClass(Subscription, null, [{
key: 'subscribe',
/**
* Listen to the given subscription and call the given func.
*
* @param {String} subscription
* @param {Function} func
* @returns {{key: String, index: Number}}
*/
value: function subscribe(subscription, func) {
if (typeof func !== 'function') {
throw new Error('Second argument to the "on" method is not a function.');
}
if (!SUBSCRIPTIONS.hasOwnProperty(subscription)) {
SUBSCRIPTIONS[subscription] = [];
}
SUBSCRIPTIONS[subscription].push(func);
return {
key: subscription,
index: SUBSCRIPTIONS[subscription].length - 1
};
}
/**
* Unsubscribe from the given subscription.
*
* @param {String} key
* @param {Number} index
*/
}, {
key: 'unSubscribe',
value: function unSubscribe(_ref) {
var key = _ref.key,
index = _ref.index;
if (SUBSCRIPTIONS.hasOwnProperty(key)) {
SUBSCRIPTIONS[key].splice(index, 1);
}
}
/**
* Emit the given subscription from the SUBSCRIPTIONS object.
* @param {String} subscription
* @param {*=} data
*/
}, {
key: 'emit',
value: function emit(subscription) {
var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
if (SUBSCRIPTIONS.hasOwnProperty(subscription)) {
SUBSCRIPTIONS[subscription].map(function (subscription) {
subscription(data);
});
}
}
}]);
return Subscription;
}();
exports.default = Subscription;