Skip to content
Advertisement

How to run a single-file javascript soundboard app from Rails 7

I have a single-file Javascript soundboard application from app academy. The code works fine, but how do I “wire” it into the Rails 7 server? I’m struggling to bridge my understanding between frontend javascript and backend Rails.

It runs if I paste the contents into app/javascript/application.js but I want to keep it a separate file: ‘app/javascript/soundboard/soundboard.js’

I am starting from a new Rails 7 project $ rails new soundboard

I added to /config/importmap.rb: pin_all_from "app/javascript/soundboard", under: "soundboard"

I added to app/javascript/application.js: import "soundboard"

My app/javascript/soundboard/soundboard.js:

const sounds = [
    'camera',
    'ding',
    'logout',
    'noise',
    'phone',
    'pop'
];

sounds.forEach((sound) => {
    const btn = document.createElement('button');
    btn.classList.add('btn');

    btn.innerText = sound;
  
    btn.addEventListener('click', ()=>{
        stopSongs();
        document.getElementById(sound).play();
    });
    
    document.getElementById('buttons').appendChild(btn);
});


function stopSongs(){
    sounds.forEach(sound =>{
        const song = document.getElementById(sound);

        song.pause();
        song.currentTime = 0;
    });
}

Do I need to add something to app/javascript/soundboard/soundboard.js Something like: module.exports=Soundboard

Advertisement

Answer

I have figured out a compromise.

Instead of the file sitting in its own directory, place it into the default directory “app/javascript/controllers” Rename it from soundboard.js to soundboard_controller.js
Its full path should be app/javascript/controllers/soundboard_controller.js

Update the HTML view where it will be used.
<div id="buttons" data-controller="soundboard"></div>
(Add the “data-controller” element with a value equal to the name of the file, excluding “_controller.js”).

There’s no need to modify the files:
config/importmap.rb
app/javascript/application.js

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement