Skip to content

Commit 441bbfd

Browse files
authored
Merge pull request #151 from gonzofish/master
Allow events to be replaced
2 parents 54bf0b2 + bd15ca9 commit 441bbfd

File tree

2 files changed

+37
-5
lines changed

2 files changed

+37
-5
lines changed

Diff for: src/__tests__/react-plotly.test.js

+15
Original file line numberDiff line numberDiff line change
@@ -164,5 +164,20 @@ describe('<Plotly/>', () => {
164164
.catch(err => done.fail(err));
165165
});
166166
});
167+
168+
describe('manging event handlers', () => {
169+
test('should add an event handler when one does not already exist', (done) => {
170+
const onRelayout = () => {};
171+
172+
createPlot({onRelayout}).then((plot) => {
173+
const { handlers } = plot.instance();
174+
175+
expect(plot.prop('onRelayout')).toBe(onRelayout);
176+
expect(handlers.Relayout).toBe(onRelayout);
177+
178+
done();
179+
});
180+
});
181+
});
167182
});
168183
});

Diff for: src/factory.js

+22-5
Original file line numberDiff line numberDiff line change
@@ -207,19 +207,36 @@ export default function plotComponentFactory(Plotly) {
207207
syncEventHandlers() {
208208
eventNames.forEach(eventName => {
209209
const prop = this.props['on' + eventName];
210-
const hasHandler = Boolean(this.handlers[eventName]);
210+
const handler = this.handlers[eventName];
211+
const hasHandler = Boolean(handler);
211212

212213
if (prop && !hasHandler) {
213-
this.handlers[eventName] = prop;
214-
this.el.on('plotly_' + eventName.toLowerCase(), this.handlers[eventName]);
214+
this.addEventHandler(eventName, prop);
215215
} else if (!prop && hasHandler) {
216216
// Needs to be removed:
217-
this.el.removeListener('plotly_' + eventName.toLowerCase(), this.handlers[eventName]);
218-
delete this.handlers[eventName];
217+
this.removeEventHandler(eventName);
218+
} else if (prop && hasHandler && prop !== handler) {
219+
// replace the handler
220+
this.removeEventHandler(eventName);
221+
this.addEventHandler(eventName, prop);
219222
}
220223
});
221224
}
222225

226+
addEventHandler(eventName, prop) {
227+
this.handlers[eventName] = prop;
228+
this.el.on(this.getPlotlyEventName(eventName), this.handlers[eventName]);
229+
}
230+
231+
removeEventHandler(eventName) {
232+
this.el.removeListener(this.getPlotlyEventName(eventName), this.handlers[eventName]);
233+
delete this.handlers[eventName];
234+
}
235+
236+
getPlotlyEventName(eventName) {
237+
return 'plotly_' + eventName.toLowerCase();
238+
}
239+
223240
render() {
224241
return (
225242
<div

0 commit comments

Comments
 (0)