8000 Allow events to be replaced by gonzofish · Pull Request #151 · plotly/react-plotly.js · GitHub
[go: up one dir, main page]

Skip to content

Allow events to be replaced #151

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 17, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
8000
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/__tests__/react-plotly.test.js
8000
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