redux-modules
Version:
A library for defining clear, boilerplate free Redux reducers.
86 lines (68 loc) • 2.7 kB
JavaScript
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _unset2 = require('lodash/unset');
var _unset3 = _interopRequireDefault(_unset2);
var _forEach2 = require('lodash/forEach');
var _forEach3 = _interopRequireDefault(_forEach2);
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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Subscription = function () {
function Subscription(store, parentSub, onStateChange) {
_classCallCheck(this, Subscription);
this.subscribe = parentSub ? parentSub.addNestedSub.bind(parentSub) : store.subscribe;
this.onStateChange = onStateChange;
this.lastNestedSubId = 0;
this.unsubscribe = null;
this.nestedSubs = {};
this.notifyNestedSubs = this.notifyNestedSubs.bind(this);
}
_createClass(Subscription, [{
key: 'addNestedSub',
value: function addNestedSub(listener) {
var _this = this;
this.trySubscribe();
this.lastNestedSubId += 1;
var id = this.lastNestedSubId;
this.nestedSubs[id] = listener;
return function () {
return (0, _unset3.default)(_this.nestedSubs, id);
};
}
}, {
key: 'isSubscribed',
value: function isSubscribed() {
return Boolean(this.unsubscribe);
}
}, {
key: 'notifyNestedSubs',
value: function notifyNestedSubs() {
(0, _forEach3.default)(this.nestedSubs, function (nestedSub) {
return nestedSub();
});
}
}, {
key: 'trySubscribe',
value: function trySubscribe() {
var _this2 = this;
if (this.unsubscribe) {
return;
}
this.unsubscribe = this.subscribe(function () {
return _this2.onStateChange(_this2.notifyNestedSubs);
});
}
}, {
key: 'tryUnsubscribe',
value: function tryUnsubscribe() {
if (this.unsubscribe) {
this.unsubscribe();
}
this.unsubscribe = null;
}
}]);
return Subscription;
}();
exports.default = Subscription;