Skip to content

Commit

Permalink
Support subclassing Observable with non-class constructor functions.
Browse files Browse the repository at this point in the history
  • Loading branch information
benjamn committed Feb 2, 2021
1 parent c9991b2 commit 2de5579
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion module.js
Original file line number Diff line number Diff line change
@@ -1 +1,26 @@
export { Observable } from "zen-observable/esm.js";
import { Observable } from "zen-observable/esm.js";

// When a non-native class constructor function attempts to subclass
// Observable, compilers like Babel and TypeScript may compile the
// super(subscriber) expression to Observable.call(this, subscriber) or
// Observable.apply(this, arguments). Calling a native class constructor
// in this way is forbidden by the ECMAScript specification, but we can
// preserve backwards compatibility by overriding the Observable.call and
// Observable.apply methods with an implementation that calls
// Reflect.construct instead, when available.

Observable.call = function (obs, sub) {
return construct(this, obs, sub);
};

Observable.apply = function (obs, args) {
return construct(this, obs, args[0]);
};

function construct(Super, self, subscriber) {
return typeof Reflect === 'object'
? Reflect.construct(Super, [subscriber], self.constructor)
: Function.prototype.call.call(Super, self, subscriber) || self;
}

export { Observable }

0 comments on commit 2de5579

Please sign in to comment.