tzkmx
6/8/2019 - 10:14 PM

Stimulus example controller on ES5 inheritance, without 3rd party dependencies

Stimulus example controller on ES5 inheritance, without 3rd party dependencies

<script src="https://unpkg.com/stimulus/dist/stimulus.umd.js"></script>

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

<script>
;(function (Stimulus) {
    var Controller = Stimulus.Controller

    function HelloController (context) {
        Controller.call(this, context)
        Object.defineProperty(
            this,
            'name',
            {
                get: function () {
                    return this.nameTarget.value
                }
            }
        )
    }
    HelloController.prototype = Object.create(Controller.prototype)
    HelloController.prototype.constructor = HelloController

    HelloController.prototype.connect = function connect () {
        console.log('Hello World')
    }

    HelloController.prototype.greet = function greet () {
        console.log('hello world', this.element, this.name)
    }

    HelloController.prototype.disconnect = function disconnect () {
        console.log('bye')
    }

    HelloController.bless = Controller.bless
    HelloController.targets = [ 'name' ]

    var application = Stimulus.Application.start()
    application.register('hello', HelloController)
})(Stimulus)
</script>