Class (ES6) template use at DAM
Table of contents
Javascript (Class based) project structure use at Dam Digital for SSR (server-side rendering) applications. You can use webpack or parcel to bundle your js project.
This project structure helps, developers, to write more modular/reusable code.
Project structure
js:
| \---modules
| +---MyModule.js
| +---vendors
| +---index.js
| +---global.js
index.js
import MyModule from ".modules/MyModule"
const modules = {
MyModule: new MyModule(), // Use default settings
MyModule2: new MyModule({
// Or use optional settings to overwrite default settings
})
};
document.addEventListener("DOMContentLoaded", function () {
modules.MyModule.init();
modules.MyModule2.init();
)}
MyModule.js
export default class MyModule {
constructor(options) {
this.options = MyModule.updateSettings(options);
this.selector = typeof this.options.selector === "string"
? document.querySelector(this.options.selector)
: this.options.selector;
this.ctas;
}
static updateSettings(userSettings) {
const defaultSettings = {
selector: ".my-selector", // Dom El or string
ctaClassName: "cta", // String
otherOption: true, // Bool
onInit: () => {} // Call back example
};
for (const attrName in userSettings) {
defaultSettings[attrName] = userSettings[attrName];
}
return defaultSettings;
}
init() {
//Do things
if(this.selector) {
this.ctas = this.selector.querySelectorAll(`.${this.options.ctaClassName}`);
this.options.onInit.call(this);
}
}
}