UNPKG

sub-events

Version:

Lightweight, strongly-typed events, with monitored subscriptions.

46 lines (45 loc) 1.62 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TimeoutEvent = void 0; exports.fromTimeout = fromTimeout; var tslib_1 = require("tslib"); var src_1 = require("../dist/src"); /** * Returns a new TimeoutEvent that triggers a fresh setTimeout on each subscribe, * and cancels the subscription after the timer event. * * And if the client cancels the subscription first, the event won't happen. */ function fromTimeout(timeout, options) { if (timeout === void 0) { timeout = 0; } return new TimeoutEvent(timeout, options); } /** * Implements a timeout event, with automatically cancelled subscriptions. * * A new timeout is started for every fresh subscriber. */ var TimeoutEvent = /** @class */ (function (_super) { tslib_1.__extends(TimeoutEvent, _super); function TimeoutEvent(timeout, options) { if (timeout === void 0) { timeout = 0; } var onSubscribe = function (ctx) { ctx.data = setTimeout(function () { ctx.event.emit(undefined, options); }, timeout); }; var onCancel = function (ctx) { clearTimeout(ctx.data); }; return _super.call(this, { onSubscribe: onSubscribe, onCancel: onCancel }) || this; } TimeoutEvent.prototype.subscribe = function (cb, options) { var sub = _super.prototype.subscribe.call(this, function () { sub.cancel(); return cb.call(options && options.thisArg); }, options); return sub; }; return TimeoutEvent; }(src_1.SubEvent)); exports.TimeoutEvent = TimeoutEvent;