Skip to content

Commit

Permalink
Convert window event service to TS
Browse files Browse the repository at this point in the history
  • Loading branch information
pugnascotia committed Dec 20, 2018
1 parent 21d84be commit 98a3dfa
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 22 deletions.
1 change: 0 additions & 1 deletion src/services/window_event/index.js

This file was deleted.

1 change: 1 addition & 0 deletions src/services/window_event/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { EuiWindowEvent } from './window_event';
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';
import { shallow } from 'enzyme';
import { EuiWindowEvent } from '.';
import { EuiWindowEvent } from './window_event';

describe('EuiWindowEvent', () => {

Expand Down Expand Up @@ -50,4 +50,4 @@ describe('EuiWindowEvent', () => {
expect(window.removeEventListener).not.toHaveBeenCalled();
});

});
});
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import { Component } from 'react';
import PropTypes from 'prop-types';

export default class WindowEvent extends Component {
type EventNames = keyof WindowEventMap;

interface Props<Ev extends EventNames> {
event: Ev;
handler: (this: Window, ev: WindowEventMap[Ev]) => any;
}

export class EuiWindowEvent<E extends EventNames> extends Component<Props<E>> {
componentDidMount() {
this.addEvent(this.props);
}

componentDidUpdate(prevProps) {
componentDidUpdate(prevProps: Props<E>) {
if (prevProps.event !== this.props.event || prevProps.handler !== this.props.handler) {
this.removeEvent(prevProps);
this.addEvent(this.props);
Expand All @@ -18,29 +23,15 @@ export default class WindowEvent extends Component {
this.removeEvent(this.props);
}

addEvent({ event, handler }) {
addEvent<Ev extends EventNames>({ event, handler }: Props<Ev>) {
window.addEventListener(event, handler);
}

removeEvent({ event, handler }) {
removeEvent<Ev extends EventNames>({ event, handler }: Props<Ev>) {
window.removeEventListener(event, handler);
}

render() {
return null;
}

}

WindowEvent.displayName = 'WindowEvent';

WindowEvent.propTypes = {
/**
* Type of valid DOM event
*/
event: PropTypes.string.isRequired,
/**
* Event callback function
*/
handler: PropTypes.func.isRequired
};

0 comments on commit 98a3dfa

Please sign in to comment.