HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Using a MutationObserver to reformat numbers in the user's locale

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theusernumbersmutationobserverusinglocalereformat

Problem

I mostly just want to make sure I've understood the specs correctly with this code, but here goes:

var nums = document.getElementsByTagName('x-number');
var observer = new MutationObserver(replaceNumerics);
var config = { childList: true, subtree: true };
observer.observe(document.body, config);
replaceNumerics(); // initial load

function replaceNumerics() {
    var l = nums.length, i, span;
    for( i=l-1; i>=0; i--) { // node list is live so iterate backwards
        span = document.createElement('span');
        span.classList.add("x-number");
        span.textContent = parseFloat(nums[i].textContent).toLocaleString();
        nums[i].parentNode.replaceChild(span,nums[i]);
    }
}


The idea is to have a custom ` tag that contains... a number, obviously. JavaScript will detect these tags, parse out the number, then render it according to the user's locale. I'm planning to do a similar thing for dates, which will be especially useful since already uses the user's locale.

My biggest concern is I think this will result in an infinite loop, as the
replaceChild call will fire the MutationObserver again... but if I understand the spec correctly, this second firing will only happen if and when all elements have been replaced (as opposed to the earlier DOMSubtreeModified event which would fire immediately), at which point there would be no more ` elements to replace and the loop would end.

Honestly this is all very unfamiliar territory to me, but I believe this should work fine... But I figured I'd subject it to public opinion before going any further with it.

Solution

One issue I'm seeing is that you're listening to the entire tree. While not an issue in small apps, it might be an issue for huge apps, with deep trees. Consider limiting it to the places where you expect your custom tag will exist.

If you are in control of the process of adding these elements to the DOM, consider doing this transformation there instead of listening to the entire DOM for you to change it. It will be easier to debug since the transformation is involved in the process of generating that element, instead of an indirect side-effect of some other operation.

You know that feeling when someone else's JavaScript re-arranges the HTML you rendered on the backend and you had to hunt it down? Same story.

Context

StackExchange Code Review Q#140585, answer score: 3

Revisions (0)

No revisions yet.