Skip to content

Instantly share code, notes, and snippets.

@dwaltrip
Created April 27, 2017 23:54
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/f77e7e4272d407f04311efd0e7d48457 to your computer and use it in GitHub Desktop.
Save dwaltrip/f77e7e4272d407f04311efd0e7d48457 to your computer and use it in GitHub Desktop.
m.mount causing memory leaks in mithril v0.2.5
<html lang="en">
<head>
<meta charset="utf-8">
<title>Memory Leak test</title>
<script src="mithril-v0.2.5.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 {
controller: function() {
this.id = (++idCounter);
console.log('Widget.oninit -- id:', this.id);
this.onclick = ()=> console.log('onclick -- id:', this.id);
this.onunload = ()=> console.log('Widget.onunload -- id:', this.id);
},
view: function(controller) {
return m('.widget', { onclick: ()=> controller.onclick() }, controller.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('test 2 -- testing v0.2.5 properly...');
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