In this very last example, called ch03_clearmessages, we make a mechanism to clear the actual message in the message bar after 10 seconds. For some applications, this is an absolutely useless feature, but for others, especially those with a less frequent notification output, this can come in handy. One way to achieve this is by manually removing the actual message after 10 seconds every time we create an output. However, there must be a more optimal and convenient way to do this. As we know that we cannot listen to change events on DOM elements without values and text contents are special DOM nodes, we will use the Mutation Observer API.
To achieve our new goal, we extend our layerTree constructor function:
var layerTree = function (options) {
[…]
var observer = new MutationObserver(function (mutations) {
if (mutations[0].target.textContent) {
var oldText = mutations[0].target.textContent;
var timeoutFunction = function () {
if (oldText !== mutations[0].target.textContent) {
oldText = mutations[0].target.textContent;
setTimeout(timeoutFunction, 10000);
} else {
oldText = '';
mutations[0].target.textContent = '';
}
};
setTimeout(timeoutFunction, 10000);
}
});
observer.observe(this.messages, {childList: true});
[…]
};Mutation Observer can notify us about a variety of changes in the observed DOM element and its children; however, it cannot track the changes in a text node. If we observe the changes in our messages element's childList, it will notify us about adding a text node or removing one (changing textContent to an empty string).
We use a recursive method to track the changes that are not observed by our observer. As we nonrecursively observe the message bar, every possible mutation event (even if someone mocks our application) will have the same target: the message bar. If we have a valid message, we store it in a variable, called oldText, and create a recursive function. This function compares the current message in the message bar with our stored message after 10 seconds. If it is the same, the function clears the message bar. If it is not, the function updates the variable and calls itself again after 10 seconds.