Skip to content

Commit

Permalink
fix(fromEvent): don't enumerate valid sources (#3594)
Browse files Browse the repository at this point in the history
* test(fromEvent): add failing test with length

* fix(fromEvent): don't enumerate valid sources

Closes #3576
  • Loading branch information
cartant authored and benlesh committed Apr 23, 2018
1 parent c23d5d6 commit 91088da
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 5 deletions.
31 changes: 31 additions & 0 deletions spec/observables/fromEvent-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,37 @@ describe('fromEvent', () => {
expect(offHandler).to.equal(onHandler);
});

it('should setup an event observable on objects with "addListener" and "removeListener" and "length" ', () => {
let onEventName;
let onHandler;
let offEventName;
let offHandler;

const obj = {
addListener: (a: string, b: Function) => {
onEventName = a;
onHandler = b;
},
removeListener: (a: string, b: Function) => {
offEventName = a;
offHandler = b;
},
length: 1
};

const subscription = fromEvent(obj, 'click')
.subscribe(() => {
//noop
});

subscription.unsubscribe();

expect(onEventName).to.equal('click');
expect(typeof onHandler).to.equal('function');
expect(offEventName).to.equal(onEventName);
expect(offHandler).to.equal(onHandler);
});

it('should error on invalid event targets', () => {
const obj = {
addListener: () => {
Expand Down
10 changes: 5 additions & 5 deletions src/internal/observable/fromEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,11 +193,7 @@ function setupSubscription<T>(sourceObj: FromEventTarget<T>, eventName: string,
handler: (...args: any[]) => void, subscriber: Subscriber<T>,
options?: EventListenerOptions) {
let unsubscribe: () => void;
if (sourceObj && (sourceObj as any).length) {
for (let i = 0, len = (sourceObj as any).length; i < len; i++) {
setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
}
} else if (isEventTarget(sourceObj)) {
if (isEventTarget(sourceObj)) {
const source = sourceObj;
sourceObj.addEventListener(eventName, handler, options);
unsubscribe = () => source.removeEventListener(eventName, handler, options);
Expand All @@ -209,6 +205,10 @@ function setupSubscription<T>(sourceObj: FromEventTarget<T>, eventName: string,
const source = sourceObj;
sourceObj.addListener(eventName, handler as NodeEventHandler);
unsubscribe = () => source.removeListener(eventName, handler as NodeEventHandler);
} else if (sourceObj && (sourceObj as any).length) {
for (let i = 0, len = (sourceObj as any).length; i < len; i++) {
setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
}
} else {
throw new TypeError('Invalid event target');
}
Expand Down

0 comments on commit 91088da

Please sign in to comment.