@iore8655/react-bus
Version:
@iore8655/react-bus is a global/local state management by pub/sub
45 lines (44 loc) • 1.88 kB
JavaScript
;
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
exports.__esModule = true;
exports.useEventBusSelector = exports.createEventBus = void 0;
var react_1 = require("react");
var react_bus_core_1 = require("./react-bus-core");
var EventBus = /** @class */ (function (_super) {
__extends(EventBus, _super);
function EventBus() {
return _super !== null && _super.apply(this, arguments) || this;
}
EventBus.prototype.dispatch = function () {
var props = [];
for (var _i = 0; _i < arguments.length; _i++) {
props[_i] = arguments[_i];
}
Object.values(this.subscribers).forEach(function (subscriber) { return subscriber.callback.apply(subscriber, props); });
};
return EventBus;
}(react_bus_core_1.Bus));
function createEventBus() {
return new EventBus();
}
exports.createEventBus = createEventBus;
function useEventBusSelector(eventBus, callback) {
var subId = react_1.useMemo(function () { return "sub-" + react_bus_core_1.context.subId++; }, []);
react_1.useEffect(function () {
eventBus.subscribe(subId, callback);
return function () { return eventBus.unsubscribe(subId); };
}, [eventBus, subId, callback]);
}
exports.useEventBusSelector = useEventBusSelector;