JSFiddle - React, Tailwind, and code Playground
by blesh
HTML
<div id="test">
<button>button</button>
<button>button</button>
<button>button</button>
<button>button</button>
<input type="text"/>
<div id="inputVal">TEST</div>
</div>
JavaScript
var traverseDom = function (fn, el) {
fn(el);
var child = el.firstChild;
console.log(child);
while (child) {
traverseDom(fn, child);
child = child.nextSibling;
}
};
function controller(fooService) {
var model = {
foo: 'bar',
called: 0,
notify: function (msg) {
fooService.foo();
console.log(msg);
},
fromInput: function(val) {
this.inputVal = val;
if(this.inputValUpdated) this.inputValUpdated();
}
};
view(document.body, model, fooService);
}
var fooService = {
foo: function () {
console.log('foo service called!');
}
};
controller(fooService);
function view(el, model, fooService) {
traverseDom(function (el) {
if (el.tagName === 'BUTTON') {
on('click', function () {
console.log('called: ' + model.called);
model.called++;
model.notify('you clicked something!');
}, el);
}
if (el.tagName === 'BODY') {
on('click', function () {
fooService.foo();
}, el);
}
if(el.tagName === 'INPUT' && el.type.toUpperCase() === 'TEXT') {
on('keyup', function () {
model.fromInput(el.value);
}, el);
}
if(el.id === 'inputVal') {
model.inputValUpdated = function (){
el.innerText = model.inputVal;
};
}
}, el);
}
function on(eventName, fn, el) {
el.addEventListener(eventName, fn);
}