Skip to content

Commit

Permalink
Make js init play nice with turbolinks
Browse files Browse the repository at this point in the history
  • Loading branch information
arielj committed Mar 19, 2021
1 parent 39e00b4 commit 13f21de
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 3 deletions.
13 changes: 12 additions & 1 deletion app/assets/javascripts/vanilla_nested.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,13 +127,24 @@
return undo;
}

document.addEventListener('DOMContentLoaded', function(){
function initVanillaNested() {
document.querySelectorAll('.vanilla-nested-add').forEach(el => {
el.addEventListener('click', addVanillaNestedFields, true);
})

document.querySelectorAll('.vanilla-nested-remove').forEach(el => {
el.addEventListener('click', removeVanillaNestedFields, true);
})
}

document.addEventListener('DOMContentLoaded', function(){
initVanillaNested();
})

// Don't run turbolinks event callback for first load, we already do it with DOMContentLoaded
const notEmpty = (obj) => Object.keys(obj).length;

document.addEventListener('turbolinks:load', function(e){
if (notEmpty(e.data.timing)) initVanillaNested();
})
})()
1 change: 1 addition & 0 deletions test/VanillaNestedTests/app/views/users/index.html.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<%= link_to 'New User', new_user_path %>
3 changes: 2 additions & 1 deletion test/VanillaNestedTests/app/views/users/new.html.erb
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
<%= render partial: 'form', locals: {user: @user} %>
<%= render partial: 'form', locals: {user: @user} %>
<%= link_to 'Back', users_path %>
3 changes: 2 additions & 1 deletion test/VanillaNestedTests/test/system/vanilla_nested_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

class VanillaNestedTest < ApplicationSystemTestCase
test "adds/removes fields" do
visit new_user_path
visit users_path
click_link 'New User'

assert_selector '#new_user'

Expand Down

0 comments on commit 13f21de

Please sign in to comment.