Search code examples
ace-editorturbolinks

Corrupted data in Ace Editor when using browser 'back' button in single page app


I'm using Ace Editor in a Rails app with TurboLinks. The editor is initialized each time a page is loaded (including when a page is loaded via the browser 'back' button):

$(document).on('turbolinks:load', function () {
    var editor = ace.edit("editor");
});

When clicking a link to another page in the application, and then clicking the browser 'back' button, the editor field is corrupted. For example, if the data in the editor is:

toto
tata

The data (displayed in the textarea of the editor) after going to another page an coming back becomes:

12tototataXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

How to prevent this from happening in my application?


Solution

  • My workaround was the following (executed at each turbolinks:load event, including when user uses 'back' button):

    1. remove the previous editor div (exists only when using 'back' button), with something like $('#editor').remove()
    2. load the content from a hidden div that is never edited
    3. add a new div for the editor, with the content to edit (something like $('#foo').after(${content})
    4. initialize the editor with ace.edit("editor");