Beginner with Rails (v5.2.1), I try to incorporate some javascript.
I have a function extendCard
in app/javascript/packs that put an event listener on all my elements with the class "card". I exported this function and imported it in app/javascript/packs/application.js. This function works when I call it from application.js.
To make it easy, let's say this function is :
function extendCard() {
let cards = document.querySelectorAll(".card");
for(let i = 0; i < cards.length; i++) {
cards[i].addEventListener("click", function() {
console.log("click works");
});
}
}
export { extendCard };
And in application.js:
import { extendCard } from './extend';
extendCard();
In views/layouts/application.html.erb I put :
<%= javascript_include_tag 'application' %>
<%= javascript_pack_tag 'application' %>
Sometimes, I need to refresh the cards displayed but want to do it with ajax. I put a remote: true
on the button that refresh the cards displayed (with filters) and I render new cards with a js.erb file stored in app/views/cards. The refresh works fine.
Now, I need to add again the event listener on those new cards. I would like to call my function extendCard
but I don't know how to reach it. When I call it, i got :
Uncaught ReferenceError: extendCard is not defined
The only thing I can do is to rewrite my function inside the js.erb (but actually I have a lot of them) and it's not very DRY.
Note that I have the webpacker gem. I don't understand it very much but I think it's related.
So, my question: how can I access easily to the functions imported in app/javascript/packs/application.js? I would like to make it in Vanilla JS if it's possible.