Is there a way to use event listeners and other js function with code mirror text area?

I am currently working on a web based code editor which supports multiple people editing the same code at once.

Until now I just used a normal text area for the code editor and it was very easy to update its content to everyone on the same socket with these following lines:

video for demonstration:

After the success with the normal text area I wanted to add some syntax highlighting, code snippets and line numbering to the site.

and for that I opted to use code mirror because of its special text areas which support all of the above while also being dynamic not like other highlighters like highlightjs and prismjs which doesn’t support the use of text areas.

Apparently I couldn’t apply normal js functions to the text area after making a code mirror object for it.

So to fix this problem I used the built in “on” function to detect changes in the code mirror text area so I could send the changes to the client and also used the “set” function to update the code mirror text area when there is a new message from the server.



But, this solution doesn’t actually work because when we use the “set” function when we get a message from the client it triggers the “on” function and then we are just in a recursion :smiley:

video demonstration:

I actually managed to fix the recursion problem by getting the previous value sent from the server and if the previous value matches with the current value from the server the text area just doesn’t change, but this fix just opened a window for other problems such as reversing the text in the text area and after writing a function that fixed that I got to a couple of other problems. To sum up using the “on” function with the “set” function for a project like mine is a mess.

Is there any way to use a code mirror text area with eventlisteners and just normal js functions like with the code from before.


This doesn’t seem hard to solve though. Set some variable while you set the value, check it in your change handler, and then clear it again, for example.

Thank you for the suggestion. To fix the problem I did something a bit more complicated but cooler lol.

I also tried resetting the text area after every new message but it make my cursor go to the start of the line in the text area.

My solution was to save the cursor position and the scroll position in the text area and set them back to how they were before the change.

It fixed the cursor issue and the backswords text issue.