Skip to content

Instantly share code, notes, and snippets.

@tdak
Last active December 6, 2020 20:47
Show Gist options
  • Save tdak/ddcb4db9312e7678810076b4e5781fa8 to your computer and use it in GitHub Desktop.
Save tdak/ddcb4db9312e7678810076b4e5781fa8 to your computer and use it in GitHub Desktop.
Turbolinks-Frame implementation for Rails, javascript and A Controller Concern
export class AjaxFrame {
updateAjaxFrame(e_id, load_turbolinks = true) {
var element = document.getElementById(e_id)
if (!element) {
return
}
var url = element.getAttribute("src")
var method = element.getAttribute("method")
var instance = this
Rails.ajax({
type: method,
url: url,
beforeSend: function( xhr ) {
xhr.setRequestHeader("X-Turbolinks-Frame", "true")
return true
},
complete: function(xhr, status) {
// update html
element.innerHTML = xhr.responseText
// if there are script tags, evaluate them by adding to head and removing it
instance.evaluateScriptTags(element)
// reload turbolinks
if (load_turbolinks) {
Rails.fire(document, "turbolinks:load")
}
}
})
}
evaluateScriptTags(element) {
var scriptElements = element.getElementsByTagName('SCRIPT');
for (var i = 0; i < scriptElements.length; i ++) {
var scriptElement = document.createElement('SCRIPT');
scriptElement.type = 'text/javascript';
if (!scriptElements[i].src) {
scriptElement.innerHTML = scriptElements[i].innerHTML;
} else {
scriptElement.src = scriptElements[i].src;
}
document.head.appendChild(scriptElement).parentNode.removeChild(script)
}
}
}
import { AjaxFrame } from "./ajax_frame"
window.updateTurbolinksPartial = function(element_id, load_turbolinks = true) {
const ajax_updater = new AjaxFrame()
ajax_updater.updateTurbolinksFrame(element_id, load_turbolinks)
}
document.addEventListener("turbolinks:load", function() {
document.querySelectorAll('turbolinks-frame[preload]').forEach(function(item, index) {
updateTurbolinksPartial(item.getAttribute("id"), false)
})
document.querySelectorAll('[data-update-turbolinks-frame]').forEach(function(item, index){
item.addEventListener("click", function(e) {
updateTurbolinksPartial(item.dataset.updateAjaxFrame)
})
})
})
<p>This is where the partial will be displayed</p>
<turbolinks-frame id="my_favourites_list" src="<%= home_path %>" method="get">
This will change after you click the button me
</turbolinks-frame>
<turbolinks-frame id="my_favourites_list_2" src="<%= home_path %>" method="get" preload='true'>
This will be loaded automatically
</turbolinks-frame>
<button type="button" name="button" data-load-turbolinks-frame="#my_favourites_list">Reload Turbolinks Frame</button>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment