ste-core
Version:
Core files for the Strongly Typed Events project.
56 lines (55 loc) • 1.74 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.PromiseSubscription = void 0;
/**
* Subscription implementation for events with promises.
*
* @export
* @class PromiseSubscription
* @implements {ISubscription<TEventHandler>}
* @template TEventHandler The type of event handler.
*/
class PromiseSubscription {
/**
* Creates an instance of PromiseSubscription.
* @param {TEventHandler} handler The handler for the subscription.
* @param {boolean} isOnce Indicates if the handler should only be executed once.
*
* @memberOf PromiseSubscription
*/
constructor(handler, isOnce) {
this.handler = handler;
this.isOnce = isOnce;
/**
* Indicates if the subscription has been executed before.
*
* @memberOf PromiseSubscription
*/
this.isExecuted = false;
}
/**
* Executes the handler.
*
* @param {boolean} executeAsync True if the even should be executed async.
* @param {*} scope The scope the scope of the event.
* @param {IArguments} args The arguments for the event.
*
* @memberOf PromiseSubscription
*/
async execute(executeAsync, scope, args) {
if (!this.isOnce || !this.isExecuted) {
this.isExecuted = true;
//TODO: do we need to cast to any -- seems yuck
var fn = this.handler;
if (executeAsync) {
setTimeout(() => {
fn.apply(scope, args);
}, 1);
return;
}
let result = fn.apply(scope, args);
await result;
}
}
}
exports.PromiseSubscription = PromiseSubscription;
;