Reputation: 2746
I am planning to use mithril.js to write a performance sensitive app, the app will have thousands of DOM elements that can be updated at any time and I have to make sure that only updated elements are getting redrawn.
My question is, is there is a way to make mithril auto-redrawing system log the DOM changes (to browser console or anywhere) so that I can review it and be absolutely sure that only the intended DOM elements are getting changed? I want to protect against my own logic mistakes and to be confident that mithril is only touching the changed elements.
Upvotes: 0
Views: 232
Reputation: 16456
You can use the W3C MutationObserver API to get the browser to log what changes are taking place in the DOM (although the API is fiddly). This can give you full knowledge of every specific modification made to the DOM.
In order to log results after a redraw, you can mount an unattached (ie never injected to the live document) component after your main application and get an empty root node to takeRecords
from the observer on Mithril's config
resolution. This code is written in the fly and untested but should give you an idea:
// Application code
// Mount an unattached component
// to log mutation records
m.mount(
document.createElement( 'div' ),
{
controller : function(){
return new MutationObserver( function( records ){
console.log( records )
} )
},
view : function( ctrl ){
return m( 'div', {
config : function( el, isInitialized ){
if( !isInitialized ){
ctrl.observe( el, {
attributes : true,
characterData : true,
childList : true
} )
}
}
} )
}
}
)
EDIT: The code I'd posted didn't work when I just tried. I updated it to provide working code. As you can see it's convoluted, unintuitive and ugly. I have ended up wanting to do this many times, and each time I've struggled with the MutationObserver API: lists of mutation records are easy enough to read, but initialising the observer is clunky and always involves copy + pasting. So I wrote a little wrapper, Muty, to make this easier. With Muty, all you need to do is muty( muty.options, el, records => console.log( records ) )
.
Upvotes: 3