From 7a809367999c5a9917d97804a2a4c97379b77b7f Mon Sep 17 00:00:00 2001 From: Thibaut Date: Sat, 18 Apr 2015 09:47:48 -0400 Subject: [PATCH] Add ability to re-run scripts on back/forward navigation ...by specifying data-turbolinks-eval=true on the ``` +Turbolinks will not re-evaluate script tags on back/forward navigation, unless their `data-turbolinks-eval` attribute is set to `true`: + +```html + +``` + Triggering a Turbolinks visit manually --------------------------------------- diff --git a/lib/assets/javascripts/turbolinks.js.coffee b/lib/assets/javascripts/turbolinks.js.coffee index 8e6f6062..bd7c9741 100644 --- a/lib/assets/javascripts/turbolinks.js.coffee +++ b/lib/assets/javascripts/turbolinks.js.coffee @@ -147,7 +147,8 @@ changePage = (doc, options) -> CSRFToken.update csrfToken if csrfToken? setAutofocusElement() - executeScriptTags() unless options.runScripts is false + scriptsToRun = if options.runScripts is false then 'script[data-turbolinks-eval="true"]' else 'script:not([data-turbolinks-eval="false"])' + executeScriptTags(scriptsToRun) currentState = window.history.state triggerEvent EVENTS.CHANGE @@ -184,8 +185,8 @@ onNodeRemoved = (node) -> jQuery(node).remove() triggerEvent(EVENTS.AFTER_REMOVE, node) -executeScriptTags = -> - scripts = document.body.querySelectorAll 'script:not([data-turbolinks-eval="false"])' +executeScriptTags = (selector) -> + scripts = document.body.querySelectorAll(selector) for script in scripts when script.type in ['', 'text/javascript'] copy = document.createElement 'script' copy.setAttribute attr.name, attr.value for attr in script.attributes diff --git a/test/javascript/iframe.html b/test/javascript/iframe.html index 051ac3b6..2a6bce09 100644 --- a/test/javascript/iframe.html +++ b/test/javascript/iframe.html @@ -21,5 +21,6 @@
permanent content
temporary content
+ diff --git a/test/javascript/turbolinks_visit_test.coffee b/test/javascript/turbolinks_visit_test.coffee index 8e31312a..1514f411 100644 --- a/test/javascript/turbolinks_visit_test.coffee +++ b/test/javascript/turbolinks_visit_test.coffee @@ -164,6 +164,7 @@ suite 'Turbolinks.visit()', -> if change is 1 @document.addEventListener 'page:fetch', -> fetchCalled = true assert.equal @window.i, 1 + assert.equal @window.k, 1 assert.equal @window.j, 1 assert.equal @document.title, 'title 2' assert.notOk @document.querySelector('#div') @@ -172,7 +173,8 @@ suite 'Turbolinks.visit()', -> , 0 else if change is 2 assert.notOk fetchCalled - assert.equal @window.i, 1 + assert.equal @window.i, 1 # normal scripts are not re-run + assert.equal @window.k, 2 # data-turbolinks-eval="true" scripts are re-run assert.equal @window.j, 1 assert.equal @document.title, 'title' assert.notOk @document.querySelector('#new-div')