Wednesday, November 13, 2024

Functional JavaScript for modern Rails

Rails 7 and 8 have been the most exciting developments for us Rails developers to come along since Rails was first released almost twenty years ago. I’ve been lucky to work on Hotwire-architected applications for a while now and I really enjoy the clean simplicity and productivity benefits of server rendering with minimum JavaScript on the front end, enabled by the Hotwire stack.

However, Stimulus.js, the “modest JavaScript framework for the HTML you already have”, forces us to use JavaScript classes. My main issue with them is that they go against the grain of JavaScript itself. They are syntactic sugar over the language’s actual design which is geared towards functional programming and composition of prototypical objects. Therefore to properly use classes you have to master “original” JavaScript and a whole extra layer of needless complexity when the original is more expressive and fun anyway.


I tried writing wrappers around the syntactic sugar to use Stimulus.js without classes, but it got very messy and convoluted and just didn’t feel right.


So this summer I started working on a library that takes the same approach for HTML as Stimulus.js but allows us to write our controller code using functional or whatever JavaScript paradigm we want, rather than forcing us into classes. I called it ATV for Actions, Targets, and Values—the core components of Stimulus.js.


Here is a page showing ATV in action: https://www.sbrew.com/atv_by_example, and here is the GitHub home page: https://github.com/timbreitkreutz/atv.js.


I’d love to hear your thoughts or suggestions!  Especially if you are an old-timey JavaScript programmer like me.