Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add attribute component:navigate #15

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions js/wire-extender.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,49 @@ document.addEventListener('DOMContentLoaded', function() {

renderComponents(components);
});

// Attribute "component:navigate"
document.addEventListener('livewire:initialized', (e) => {
// If a "component:navigate" anker is clicked, load the given component
const componentNavigateClick = (event) => {
event.preventDefault();

let component = event.target.getAttribute('data-component');
let params = event.target.getAttribute('data-params');

let livewireElem = event.target.closest("livewire");
livewireElem.setAttribute('data-component', component);
livewireElem.setAttribute('data-params', params ?? '');

renderComponents([{name: component, params: params}]);
};

// Register click event for all elements with attribute "component:navigate"
const componentNavigateElementUpdated = ({el}) => {
if (el == undefined) {
document.querySelectorAll('[component\\:navigate]').forEach(
(elem) => elem.addEventListener('click', componentNavigateClick)
);
return;
}

if (el.hasAttribute('component:navigate')) {
el.addEventListener('click', componentNavigateClick);
return;
}
};

// Trigger event for every livewire update cycle
window.Livewire.hook('morph.updated', componentNavigateElementUpdated);

// Use observer to detect if the component has been replaced
const componentNavigateObserver = new MutationObserver( () => {
componentNavigateElementUpdated({ undefined });
});
document.querySelectorAll('livewire').forEach((elem) => {
componentNavigateObserver.observe(elem, {attributes: false, childList: true, subtree: true});
});

// Initial call to register click events
componentNavigateElementUpdated({ undefined });
});