Skip to content

Commit

Permalink
Added mutation observer to observe matrix changes and add event liste…
Browse files Browse the repository at this point in the history
…ners.
  • Loading branch information
HichemBenali committed Jun 21, 2022
1 parent 99b7a1b commit 9af5d09
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
2 changes: 1 addition & 1 deletion public/mix-manifest.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

32 changes: 27 additions & 5 deletions resources/js/controllers/listener_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ import ApplicationController from "./application_controller";
export default class extends ApplicationController {
listenerEvent = () => this.render();

/**
* Mutation Observer for matrix.
* @type {null|MutationObserver}
*/
observer = null;

/**
*
*/
Expand All @@ -14,23 +20,39 @@ export default class extends ApplicationController {
*
*/
addListenerForTargets() {
this.observer.disconnect();

this.targets.forEach(name => {
document.querySelectorAll(this.selectorFromTarget(name))
.forEach((field) =>
field.addEventListener('change', this.listenerEvent, {
once: true
})
.forEach((field) => {
field.addEventListener('change', this.listenerEvent, {
once: true
});

let matrix = field.closest('table.matrix tbody');
if(!!matrix) this.addListenerToMatrix(matrix);
}
);
});
}

/**
*
* @param {Element} matrix
*/
addListenerToMatrix(matrix) {
let options = { attributes: false, childList: true, subtree: false };
this.observer = new MutationObserver(() => this.addListenerForTargets());
this.observer.observe(matrix, options);
}

/**
*
* @param {string} name
* @return {string}
*/
selectorFromTarget(name) {
if(name.includes('*')) {
if (name.includes('*')) {
return name.split('*').reduce((prev, cur) => prev + `[name*="${cur}"]`, '');
}
return `[name="${name}"]`;
Expand Down

0 comments on commit 9af5d09

Please sign in to comment.