Working With Javascript

Setting up a vanilla JS component

Create module in vanilla-modules folder e.g. ‘/src/js/vanilla-modules/MyUniqueComponentName.js’

Set up the following scaffolding within the JS file:

import Module from '../scaffolding/vanilla/VanillaModuleBase'

export default class MyUniqueComponentName extends Module {
    constructor(){
        super(...arguments)
        this.setUpMethod()
    }
    setUpMethod() {
       console.log(this.root, 'My unique component!')
    }
}

The variable this.root is initalized in vanilla module base class, this targets the modules root DOM element (explained below).

Next up, import your module into src/js/main.js file:

import Accordion from './vanilla-modules/MyUniqueComponentName'

Add to existing vanilla module loader:

new VanillaModuleLoader ([
    ...
    {
        name: 'MyUniqueComponentName',
        instance: MyUniqueComponentName
    }
])

Setting up the view

Set up div/tag in your new view with a data attribute called ‘data-vanilla-module’ with the value of your corresponding JS module:

<div data-vanilla-module="MyUniqueComponentName">...</div>

The variable this.root within your module class will target the above DOM/HTML element, this means you can scope your querySelectors to the specific module e.g.

View:

<div data-vanilla-module="MyUniqueComponentName">
    <button>Click me!</button 
</div>

JS:

    constructor(){
        super(...arguments)
        this.button = this.root.querySelector('button')
        this.setUpMethod()
    }
    setUpMethod() {
       button.addEventListener('click', (e) => {
            e.preventDefault();
            console.log('Button Clicked!')
       })
    }

General Guidelines:

  • Use ES6 JS e.g. make use of let, const arrow functions, array functions etc.
  • Use axios for API calls

By default the vanilla module loader will loop over and try to target multiple modules on the page e.g. you could have multiple accordions.

If you know that there is only a single instance of this module you can set it to be a single module via the module loader:

new VanillaModuleLoader ([
    ...
    {
        name: 'MyUniqueComponentName',
        instance: MyUniqueComponentName
        isSingleModule: true
    }
])