directive
html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<ul>
<li helloworld></li>
<li helloworld></li>
<li helloworld></li>
</ul>
<button
type="button"
on-click="changeButtonName(event)">
Button
</button>
<script>
const Directive = (() => {
const store = new Set();
const define = ({name, bind}) => {
store.add({ name, bind });
};
const parseAttr = (_attr) => {
let attr = _attr;
if(attr.indexOf('(') > -1){
attr = attr
.replace('(',',')
.replace(')','');
}
return attr.split(',');
};
const render = (parentSelector) => {
const parent = document.querySelector(parentSelector);
store.forEach((directive) => {
const finedElems = parent.querySelectorAll(`[${directive.name}]`);
finedElems.forEach((elem) => {
const directiveValue = parseAttr(elem.getAttribute(directive.name));
directive.bind(elem, directiveValue);
});
});
};
return {define, parseAttr, render}
})();
</script>
<script>
Directive.define({
name: 'on-click',
bind: (elem, [callbackName, hasEvent]) => {
elem.onclick = (event) => {
window[callbackName].call(elem, hasEvent ? event : undefined);
};
}
});
Directive.define({
name: 'helloworld',
bind: (elem) => {
elem.innerHTML = 'Hello World';
}
});
Directive.render('body');
function changeButtonName(event){
this.innerHTML = 'Changed Button';
}
</script>
</body>
</html>