Skip to content

DOM Manuplation


html
<!DOCTYPE html>

<p id="test" z-on="arg.test:console.log('hello world')">hello</p>
<p>world</p>

<script>
function directive(name, callback, scope = document.body) {
    const elements = scope.querySelectorAll(`[z-${name}]`);
    const regex = /^(.*?)(?::\((.*?)\)|:(\{[^}]*\})|:(\[[^\]]*\])|:(.*))/;

    elements.forEach(el => {
        const content = el.getAttribute(`z-${name}`)
        const matches = content.match(regex);

        if (content !== null && matches) {
            let [, prfx, value1, value2, value3, value4] = matches;

            const modifiers = prfx.split(".");
            const arg = modifiers.shift();
            const value = value1 || value2 || value3 || value4;
            
            callback({ el, arg, modifiers, value });
        } else {
            callback({ el, value: content });
        }

        
    });
}

directive('on', ({ el, arg, modifiers, value }) => {
    console.log(el, arg, modifiers, value)
})

</script>