home ~ projects ~ socials

Element Based JavaScript Object Framework

This is just playing around with an idea. That goal is not to make a full featured framework. Just to poke at an idea of a quick script for making things without a having to install anything or run build steps.

TODO

    Look at id: 2f5jbveu for the approach for setting up with a module

HTML

<div class="exampleWrapper"></div>

Output

JavaScript

document.addEventListener('DOMContentLoaded', () => {
  const w = new Widget()
  w.init()
})

JavaScript

class Widget {
  constructor() {
    this.data = {}
    this.data.itemList = ['alfa', 'bravo', 'charlie', 'delta']
  }

  appendTo(parent, el) {
    parent.appendChild(el)
    return el
  }

  getEl(el) {
    return document.querySelector(el)
  }

  init() {
    this.makeList()
  }

  makeEl(kind, classes = [], attrs = [], data = [], content = '') {
    const el = document.createElement(kind)
    classes.forEach((c) => el.classList.add(c))
    attrs.forEach((attr) => el[attr[0]] = attr[1])
    data.forEach((d) => el.dataset[d[0]] = d[1])
    if (content !== '') { el.innerHTML = content }
    return el
  }

  makeList() {
    this.mainList = this.appendTo.call(this, 
      this.getEl(`.exampleWrapper`),
      this.makeEl('ul')
    )
    this.items = this.data.itemList.map((item) => {
      this.appendTo.call(this, 
        this.mainList,
        this.makeEl('li', [], [], [], item)
      )
    })
  }
}
-- end of line --