Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draft.JS: the proper way to detect content change

There is onChange event, but it fires also when carret moves or navigation (arrows etc) button being pushed.

I want to detect if content was changed. Basically i need to detect this only once when the very first change occur. The dumb way "compare content" may work here, but this is an anti-pattern because this task is too resources-expensive.

like image 436
stkvtflw Avatar asked Jan 25 '17 09:01

stkvtflw


1 Answers

Since Draft uses an immutable data structure, it doesn't have to be that resource heavy – comparing references should be enough:

onChange(newEditorState) {
  const currentContent = this.state.editorState.getCurrentContent()
  const newContent = newEditorState.getCurrentContent()

  if (currentContent !== newContent) {
    // Content has changed
  }
}
like image 171
tobiasandersen Avatar answered Oct 27 '22 18:10

tobiasandersen