MDN JS Docs suggested to use MutationObsorver as oppsoed to deprecated DOMSubtreeModified event

This commit is contained in:
Warren Buckley
2018-10-23 15:13:35 +01:00
parent 60b575825d
commit a8ac9cf8f2

View File

@@ -5,22 +5,52 @@ angular.module("umbraco.directives")
restrict: 'A', //Can only be used as an attribute
link: function (scope, element, attrs) {
//When the current element DOM subtree is modified
element.on('DOMSubtreeModified', function(e){
//Check if any child items in e.target contain an input
var jqLiteEl = angular.element(e.target);
var childInputs = jqLiteEl.find('input');
//Use DOM Mutation Observer
//Select the node that will be observed for mutations (native DOM element not jQLite version)
var targetNode = element[0];
console.log('jQLite childInputs', childInputs);
// Options for the observer (which mutations to observe)
var config = { attributes: false, childList: true, subtree: false };
//For each item in childInputs - override or set HTML attribute tabindex="-1"
angular.forEach(childInputs, function(element){
console.log('item in loop', element);
// Callback function to execute when mutations are observed
var callback = function(mutationsList, observer) {
for(var mutation of mutationsList) {
//TODO: Note we updating way too many times from the DOMSubtreeModified event - is this expensive?
angular.element(element).attr('tabindex', '-1');
});
console.log('mutation', mutation);
//DOM items have been added or removed
if (mutation.type == 'childList') {
//Check if any child items in mutation.target contain an input
var jqLiteEl = angular.element(mutation.target);
var childInputs = jqLiteEl.find('input');
//For each item in childInputs - override or set HTML attribute tabindex="-1"
angular.forEach(childInputs, function(element){
console.log('item in loop', element);
//TODO: Note we updating way too many times from the DOMSubtreeModified event - is this expensive?
angular.element(element).attr('tabindex', '-1');
});
}
}
};
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
//GO GO GO
observer.observe(targetNode, config);
//TODO: Unsure if we need to do this - to ensure the browser not trying to notify us still
//When we browse away from the page
element.on('$destroy', function(e){
console.log('element with disable-tabindex attribute is destoryed');
//Remove/stop the observer
observer.disconnect();
});
}