Skip to content

Commit

Permalink
Merge pull request #151 from gonzofish/master
Browse files Browse the repository at this point in the history
Allow events to be replaced
  • Loading branch information
dmt0 authored Oct 17, 2019
2 parents 54bf0b2 + bd15ca9 commit 441bbfd
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 5 deletions.
15 changes: 15 additions & 0 deletions src/__tests__/react-plotly.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -164,5 +164,20 @@ describe('<Plotly/>', () => {
.catch(err => done.fail(err));
});
});

describe('manging event handlers', () => {
test('should add an event handler when one does not already exist', (done) => {
const onRelayout = () => {};

createPlot({onRelayout}).then((plot) => {
const { handlers } = plot.instance();

expect(plot.prop('onRelayout')).toBe(onRelayout);
expect(handlers.Relayout).toBe(onRelayout);

done();
});
});
});
});
});
27 changes: 22 additions & 5 deletions src/factory.js
Original file line number Diff line number Diff line change
Expand Up @@ -207,19 +207,36 @@ export default function plotComponentFactory(Plotly) {
syncEventHandlers() {
eventNames.forEach(eventName => {
const prop = this.props['on' + eventName];
const hasHandler = Boolean(this.handlers[eventName]);
const handler = this.handlers[eventName];
const hasHandler = Boolean(handler);

if (prop && !hasHandler) {
this.handlers[eventName] = prop;
this.el.on('plotly_' + eventName.toLowerCase(), this.handlers[eventName]);
this.addEventHandler(eventName, prop);
} else if (!prop && hasHandler) {
// Needs to be removed:
this.el.removeListener('plotly_' + eventName.toLowerCase(), this.handlers[eventName]);
delete this.handlers[eventName];
this.removeEventHandler(eventName);
} else if (prop && hasHandler && prop !== handler) {
// replace the handler
this.removeEventHandler(eventName);
this.addEventHandler(eventName, prop);
}
});
}

addEventHandler(eventName, prop) {
this.handlers[eventName] = prop;
this.el.on(this.getPlotlyEventName(eventName), this.handlers[eventName]);
}

removeEventHandler(eventName) {
this.el.removeListener(this.getPlotlyEventName(eventName), this.handlers[eventName]);
delete this.handlers[eventName];
}

getPlotlyEventName(eventName) {
return 'plotly_' + eventName.toLowerCase();
}

render() {
return (
<div
Expand Down

0 comments on commit 441bbfd

Please sign in to comment.