Skip to content

Instantly share code, notes, and snippets.

@martsie
Last active November 26, 2019 05:44
Show Gist options
  • Save martsie/e82277758820efe8a518e7a71b6d026b to your computer and use it in GitHub Desktop.
Save martsie/e82277758820efe8a518e7a71b6d026b to your computer and use it in GitHub Desktop.
Lewagon Vanilla JS Plugin template
// packs/application.js
import { initMyPlugin } from './plugins/MyPlugin';
// Always add a js- prefixed class to your elements when targeting to create a separation
// of concerns between classes you use to style and classes you use to do javascript.
initMyPlugin('.js-my-widget');
/*
Example safe-executing JS script for Lewagon.
packs/plugins/myPlugin.js
*/
export const initMyPlugin = (selector) => {
const elements = Array.from(document.querySelectorAll(selector));
return elements.map(el => new MyPlugin(el));
};
class MyPlugin {
// Keep the constructor lean, don't add anything more to this.
constructor(el) {
this.el = el;
// Bind event listener methods to class.
this.onButtonClick = this.onButtonClick.bind(this);
this.init();
}
init() {
// Do whatever you need to do here. Get as spaghetti western as
// you want and refactor later.
// You can find elements within the element too.
// Use the El suffix on variable names that reference an element.
const buttonEl = this.el.querySelector('.js-button');
// Add event listeners.
buttonEl.addEventListener('click', this.onButtonClick);
}
// Events. Make sure this are all bound in the constructor.
onButtonClick(e) {
e.preventDefault();
alert('Clicked button!');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment