David Bourea

David Boureau

I create web applications

StimulusJS with plain old JavaScript

11 February, 2018

StimulusJS

StimulusJS is a new Javascript framework from Basecamp. It’s a framework for already rendered DOM.

I plan to write an article about the tool, as if some people already did.

Make it work with plain old Javascript

StimulusJS is to be used with advanced ES6 class features.

This is why it doesn’t work yet without a proper build system, the documentation needs to be updated on that point.

You need either Webpack, or Babel with a special configuration, or Coffeescript (which also transpile into ES3).

To be able to be used in any web project, StimulusJS needs the ability to let the developper use it in plain old Javascript.

The hack

All class-related libraries for Javascript are very nice, but are neither compatible with each other, nor with ES6.

Fortunately, Classtrophobic does the job. It allow the developer to declare classes in plain old Javascript, that are compatible with the ones generated by Babel.

Example

Github repository

Demo

Just insert Classtrophobic amongst the scripts, and the code example of StimulusJS works with very little adaptation:

<html>

<head>
  <title>Stimulus Sandbox</title>
  <script src="./classtrophobic-es5.js"></script>
  <script src="./stimulus.js"></script>
</head>

<body>
  
  <div data-controller="hello">
    <input type="text" data-target="hello.name">
    <button data-action="click->hello#greet">
      Greet in the console
    </button>
  </div>

<script type="text/javascript">

    var application = Stimulus.Application.start();
    
    var Hello = Class({
      extends: Stimulus.Controller,
      static: {
        targets : [ "name" ]
      },
      greet: function() {
        var element = this.nameTarget;
        var name = element.value;
        console.log("Hello : " + name);
      }
    });
    
    application.register("hello", Hello);
</script>
</body>

</html>