diff --git a/src/ckeditor.js b/src/ckeditor.js index 359d0dc..68a514e 100644 --- a/src/ckeditor.js +++ b/src/ckeditor.js @@ -15,6 +15,7 @@ class CKEditor extends React.Component { //Bindings this.onLoad = this.onLoad.bind(this); + this.registerEventHandlers = this.registerEventHandlers.bind(this); //State initialization this.state = { @@ -25,15 +26,19 @@ class CKEditor extends React.Component { //load ckeditor script as soon as component mounts if not already loaded componentDidMount() { - if(!this.props.isScriptLoaded){ + if (!this.props.isScriptLoaded) { loadScript(this.props.scriptUrl, this.onLoad); - }else{ + } else { this.onLoad(); } } componentWillUnmount() { this.unmounting = true; + if (this.editorInstance) { + this.editorInstance.removeAllListeners(); + window.CKEDITOR.remove(this.editorInstance); + } } onLoad() { @@ -54,14 +59,42 @@ class CKEditor extends React.Component { this.props.content ); - //Register listener for custom events if any - for(var event in this.props.events){ - var eventHandler = this.props.events[event]; + //Register listener for change event. + //PS - This prop is now deprecated since change event can now be directly listened via events prop. + /* + ******** DEPRECATED ******** + this.editorInstance.on("change", () => { + const content = this.editorInstance.getData(); + + //call onChange callback if present + if(this.props.onChange){ + this.props.onChange(content); + } + }); + */ + + this.registerEventHandlers(this.props.events); + } - this.editorInstance.on(event, eventHandler); + registerEventHandlers(events, prevEvents) { + prevEvents = prevEvents || {}; + + //Register listener for custom events if any + for (var event in events) { + if (events[event] !== prevEvents[event]) { + var prevEventHandler = prevEvents[event]; + if (prevEventHandler) this.editorInstance.removeListener(event, prevEventHandler); + + var eventHandler = events[event]; + this.editorInstance.on(event, eventHandler); + } } } + componentWillReceiveProps(nextProps) { + if (this.editorInstance) this.registerEventHandlers(nextProps.events, this.props.events); + } + render() { return
; }