Last active
October 13, 2020 21:38
-
-
Save printercu/e202851c370ffc38bcdedeb8300d417e to your computer and use it in GitHub Desktop.
Turbolinks adapter for vue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Copyright (c) Maxim Melentiev. | |
# This source code is licensed under the MIT license. | |
# | |
# Inspired by | |
# https://github.com/jeffreyguenther/vue-turbolinks/blob/master/index.js | |
# but changed to support going back to cached page with vue instance. | |
# Original version will keep instance created from cache along with new one. | |
plugin = | |
instances: [] | |
bind: -> | |
# Destroy instances on current page when moving to another. | |
document.addEventListener 'turbolinks:before-cache', -> plugin.cleanupInstances() | |
# Destroy left instances when previous page has disabled caching. | |
document.addEventListener 'turbolinks:before-render', -> plugin.cleanupInstances() | |
# Clear instances on curent page which are not present anymore. | |
document.addEventListener 'turbolinks:load', -> | |
plugin.cleanupInstances (x) -> document.contains(x.$el) | |
cleanupInstances: (keep_if) -> | |
result = [] | |
for instance in plugin.instances | |
if keep_if?(instance) | |
result.push(instance) | |
else | |
instance.$destroy() | |
plugin.instances = result | |
Mixin: | |
beforeMount: -> | |
# If this is the root component, | |
# we want to cache the original element contents to replace later. | |
# We don't care about sub-instances, just the root | |
if @ == @$root | |
plugin.instances.push(@) | |
@$originalEl = @$el.outerHTML | |
destroyed: -> | |
# We only need to revert the html for the root component. | |
@$el.outerHTML = @$originalEl if @ == @$root | |
install: (Vue, _options) -> | |
plugin.bind() | |
Vue.mixin(plugin.Mixin) | |
# export default plugin | |
# or: | |
# Vue.TurbolinksAdapter = plugin | |
# plugin.bind() |
Hi @RensAlthuis I've just added a note to the header. I'm glad that it's useful for you.
Ah thank you so much!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey @printercu I'd like to use this code in a project. But technically, since you didn't specify a license, this is copyrighted and I can't use it.
Would you be willing to include an open-source license in this Gist? Maybe add the MIT license file, I would be really grateful!