Where to store general shared javascript functions?

I’m using Rails 7 with importmap-rails and propshaft, trying to move everything to turbo or stimulus.

Within my Stimulus Controller, I need to make an AJAX call to a third party API to retrieve JSON.

Previously, using jQuery I’d using $.ajax, but trying to use plain javascript it turns out you need to use JSONP to avoid Cross-Origin errors, yet new XMLHttpRequest(); doesn’t support JSONP.

With that, I’m creating my own getJSONP function based on getJSONP.js | The Vanilla JS Toolkit to call within the connect() method of my stimulus controller. I’d like to store this function somewhere so it’s available to all my controllers.

Where/how do I do that? I’m stuck back in the pre-2010 world of js and can’t figure it out. Putting it just in application.js didn’t work :sob:

To circle back to this, what I’ve gone with is I’ve created an application_controller.js for Stimulus as suggested here: Application Controller - Better StimulusJS

What that looks like is:

app/javascript/controllers/application_controller.js

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {

  // Add all my random JS functions here.
  
  boom(message) {
    console.log(message)
  }

}

Then I adjust my already existing controllers to extend from ApplicationController instead of Controller:

app/javascript/controllers/user_controller.js

import ApplicationController from "controllers/application_controller"

export default class extends ApplicationController {

  connect () {
    super.boom('boomshakalaka')
  }

That’s working great :partying_face:

If interested, the JSONP approach I ended-up going with is How to make a JSONP request from Javascript without JQuery? - Stack Overflow

1 Like

Hey has helpers, initializers and lib. I’m following that approach too.