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
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')
}