Browse Source

Add Turbolinks render hook

jameslkingsley 5 years ago
parent
commit
bc3346fc34
1 changed files with 13 additions and 5 deletions
  1. 13 5
      src/index.js

+ 13 - 5
src/index.js

@@ -18,10 +18,11 @@ const Spruce = {
 
         this.emit('init')
 
-        document.querySelectorAll('[x-subscribe]').forEach(el => {
-            el.setAttribute('x-init', buildInitExpression(el))
-            el.removeAttribute('x-subscribe')
-        })
+        if ('Turbolinks' in window) {
+            document.addEventListener('turbolinks:render', this.attach)
+        }
+        
+        this.attach()
 
         this.stores = createObservable(this.stores, {
             set: (target, key, value, oldValue) => {
@@ -42,6 +43,13 @@ const Spruce = {
         }
     },
 
+    attach() {
+        document.querySelectorAll('[x-subscribe]').forEach(el => {
+            el.setAttribute('x-init', buildInitExpression(el))
+            el.removeAttribute('x-subscribe')
+        })
+    },
+
     store: function (name, state) {
         if (! this.stores[name]) {
             this.stores[name] = state
@@ -102,4 +110,4 @@ window.deferLoadingAlpine = function (callback) {
     deferrer(callback)
 }
 
-export default Spruce
+export default Spruce