jquery - Turbolinks duplicating rich text editor -
i'm using rails 5 turbolinks , summernote simple wysiwyg editor. i'm loading plugin on turbolinks:load, this:
$(document).on('turbolinks:load', function() { $('[data-provider="summernote"]').each(function(){ $(this).summernote({ }); }) }
but if navigate somewhere else , press button on browser editor gets duplicated
i tried jquery document ready, plugin doesn't loaded unless page load first 1 editor. please help.
i know there changes turbolinks between rails 4.2 , 5, here take on this.
in many cases, can adjust code listen turbolinks:load event, fires once on initial page load , again after every turbolinks visit.
https://github.com/turbolinks/turbolinks#running-javascript-when-a-page-loads
if above quote right, each time visit page (whether on ready
or page:load
) turbolink trigger fire.
now 1 misconception turbolinks visiting page destroys javascript elements within page.
this false, in fact big issue turbolink in rails 4.2.
you can test out (don't have take word it) doing:
$(document).ready(...)
then reload page, navigate away, come back.
if code still instantiated, proves code persisted.
if case, need rethink how working js.
so code persists , on
means every time, want happen once whether page loaded browser or turbolinks.
i think appropriate solution be:
$(document).one('turbolink:load', ...)
edit
i able recreate issue perfectly.
i think behavior is... correct.
the issue follows:
- summernote creates elems below
<div data-provide="summernote"
setsstyle="display:none;
- all elements (including added summernote) cached.
- then when code re-executed (as should unless presentational so) code finds
<div data-provide="summernote">
chilling above , recreates summernote box.
now comes philosophical question change solution applies:
should cache page?
if answer yes, option use fact summernote set's div hidden our advantage.
$(document).on('turbolinks:load', function() { $('[data-provider="summernote"]').each(function() { if ($(this).is(":visible")) $(this).summernote() }) })
note differentiate instantiated summernote div differently (i.e. adding class, or data attribute), convenient way.
otherwise, not caching page, re-executed , good.
p.s. there complications while using turbolinks, not because it's bad tool. because js libraries work off assumptions of how page cycles work , turbolinks complete overhaul of how page cycles work.
hope helps not provide solution understanding!
cheers
Comments
Post a Comment