Skip to content

Instantly share code, notes, and snippets.

@dwaltrip
Last active April 27, 2017 23:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dwaltrip/519d565c9be1c70aa09fb014deb0c480 to your computer and use it in GitHub Desktop.
Save dwaltrip/519d565c9be1c70aa09fb014deb0c480 to your computer and use it in GitHub Desktop.
Testing for memory leaks in `m.mount` (in mithril.js v1.1.1)
<html lang="en">
<head>
<meta charset="utf-8">
<title>Memory Leak test</title>
<script src="mithril-v1.1.1.js"></script>
<style>
body { padding: 15px; margin: 0; }
#widget-container {
width: 340; height: 340; display: flex; flex-wrap: wrap; margin-top: 10px;
}
.widget {
height: 30px; width: 30px; margin: 2px; border: 1px solid #777; font-size: 10px;
display: flex; justify-content: center; align-items: center;
box-sizing: border-box; user-select: none;
}
.widget:hover { cursor: pointer; }
</style>
</head>
<body>
<button onclick="toggleWidgets()">Toggle widgets</button>
<div id="widget-container"></div>
<script>
var NUM_WIDGETS = 100;
var idCounter = 0;
function getWidget() {
return {
oninit: function() {
this.id = (++idCounter);
console.log('Widget.oninit -- id:', this.id);
},
onclick: function() { console.log('onclick -- id:', this.id); },
onbeforeremove: function() { console.log('Widget.onbeforeremove -- id:', this.id); },
view: function() {
return m('.widget', { onclick: ()=> this.onclick() }, this.id);
}
};
}
var rootNodes = [];
var isShowingWidgets = false;
function toggleWidgets() {
rootNodes.forEach(function(rootNode) {
if (isShowingWidgets) {
var node = rootNode.children[0];
m.mount(node, null);
node.remove();
} else {
var node = buildWidgetMountPoint(rootNode);
m.mount(node, getWidget());
}
});
isShowingWidgets = !isShowingWidgets;
}
function buildWidgetMountPoint(parent) {
var node = document.createElement('div');
node.classList.add('widget-wrapper');
parent.appendChild(node);
return node;
}
function setup() {
console.log('-- testing again with mithril v1.1.1 -- test 2');
var container = document.getElementById('widget-container');
for (var i = 1; i <= NUM_WIDGETS; i++) {
var rootNode = document.createElement('div');
rootNode.id = 'root-' + i;
rootNode.classList.add('root-node');
container.appendChild(rootNode);
rootNodes.push(rootNode);
}
toggleWidgets();
}
setup();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment