<div class="view" data-controller="clicker"></div>
<div class="view" data-controller="clicker"></div>
<div class="view" data-controller="clicker"></div>
<div class="view" data-controller="monitor"></div>


<script type="text/template" id="tmpl-clicker">
<div class="clicker">
    <p>You clicked
    <span class="res">0</span>
    times
    <button class="autobind" data-click="inc">Click Here</button>
  </div>
</script>

<script type="text/template" id="tmpl-monitor">
<div class="monitor" >
  <div class="autobind" data-mousemove="update" style="width:300px;height:300px;border:2px solid blue">
    <span class="x"></span>
    <span class="y"></span>
  </div>
</div>
</script>

const EVENTS = ['click', 'mousemove'];

const views = document.querySelectorAll('.view');

class BaseController {
  constructor(el) {
    const templateId = 'tmpl-' + this.constructor.name.toLowerCase();
    
    const _html = document.getElementById(templateId).innerHTML;
    el.innerHTML = _html;
    this.el = el;

    const tobind = el.querySelectorAll('.autobind');
    for (let i=0; i<tobind.length; i++) {
      for (let evName of EVENTS) {
        const handlerName = tobind[i].dataset[evName];
        if (!handlerName) continue;

        tobind[i].addEventListener(evName, this[handlerName].bind(this));
      }
    }
  }
}

class Clicker extends BaseController {
  constructor(el) {
    super(el);
    this.val = 0;
  }

  inc() {
    this.el.querySelector('.res').textContent = ++this.val;
  }
}

class Monitor extends BaseController {
  constructor(el) {
    super(el);
  }

  update(ev) {
    this.el.querySelector('.x').textContent = ev.offsetX;
    this.el.querySelector('.y').textContent = ev.offsetY;
  }
}


const CONTROLLERS = {
  clicker: Clicker,
  monitor: Monitor,
};

for (let i=0; i<views.length; i++) {
  const v = views[i];
  if (!v.dataset.controller) continue;
  
  new CONTROLLERS[v.dataset.controller](v);  
}
View Compiled

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.