What is a better solution for initializing jquery plugins on a browser button that do not just transform elements when using turboprops in Rails 5, for example, masterslider (photo gallery) or spot (carousel) than reloading the page, as I do below?
document.addEventListener 'turbolinks:load', -> slickElementsPresent = $('.event-card').find('div.slick-slide')[0] if slickElementsPresent? window.location.reload(); else $('.event-card').each -> $(@).not('.slick-initialized').slick { infinite: false, nextArrow: $(@).find('.event-more-details-button'), prevArrow: $(@).find('.event-card-slide-back-button') }
To be clear, I check if there are "turbolinks: load", if there are any html elements that will be present only if the plugin has been initialized, if so, then refresh the page, because although there are elements , the plugin is not initialized. And then I initialize the plugin on all elements that have the class I want in.
Some people have run into this problem here: https://github.com/turbolinks/turbolinks/issues/106 , where someone points out
I just want to add for those who have similar problems that make idempotent initialization not necessarily a solution in some cases. By doing this with dataTables, I can avoid duplicate items. However, the cached versions of the elements on the page associated with the plugin no longer work in the reverse browser, as it seems that the plugin is not initialized on the cached page.
Reload the page if the plugin has already changed the DOM because it is removed from the cache when someone presses the back button, it just seems pretty bad, but this is the best I came up with, so I turn to the world for more ideas!
UPDATE:
So, some jquery plugins have excellent undo / destroy methods, and if in this case it is better to add an event listener to "turbolinks:before-cache" and then call this method as follows:
document.addEventListener "turbolinks:before-cache", -> $('.event-card').each -> $(@).slick('unslick');
but some jquery plugins do not have destruction functions or destroy functions that achieve this. Like masterslider, there is a function $('your-slider-element').masterslider('destroy') , but it will not “cancel” the javascript style that it applies to your html, as it simply gets rid of it completely, and therefore, when you return to the page from the browser back or forward, the slider simply does not exist, because the html element with which it is launched has been destroyed. This means that for some plugins, the best answer I have is to completely reload the page when the page on which they are located moves back and forth through the browser buttons.