createDiv(text, parent) { if (this.divPool.length > 0) { console.log(`get from pool, pool count:${this.divPool.length}`); let div = this.divPool.shift(); div.innerText = text; parent.appendChild(div); return div; } else { console.log(`create a new div, because pool count:${this.divPool.length}`); let div = document.createElement('div'); div.innerText = text; parent.appendChild(div); return div; } } removeDiv(node, parent) { parent.removeChild(node); this.recover(node); console.log(`when ui remove div, restore this div, now pool has: ${this.divPool.length}`); } recover(node) { this.divPool.push(node); } }
var circleFactory = (function () { var circlePool = []; var parent = document.querySelector('.flyweight-body'); return { create: function () { if (circlePool.length !== 0) { return circlePool.shift(); } else { var div = document.createElement('div'); div.setAttribute('class', 'flyweight-child'); parent.appendChild(div); return div; } }, recover: function (dom) { return circlePool.push(dom); }, remove: function (oldPool) { for (var i = 0; i < oldPool.length; i++) { parent.removeChild(oldPool[i]); } } } })();
var renderCircle = (function () { var circlePool = []; returnfunction (number) { console.log('length: ' + circlePool.length); for (var j = 0; j < number.length; j++) { circleFactory.recover(circlePool.pop()); circlePool.length = circlePool.length - 1; } console.log('length: ' + circlePool.length); circleFactory.remove(circlePool); circlePool = []; for (var i = 0; i < number; i++) { var circle = circleFactory.create(); circle.style.left = Math.random() * 700 + 'px'; circle.style.top = Math.random() * 400 + 'px'; circlePool.push(circle); } } })();
var init = function () { Event.listen('draw-circle', function (args) { var number = Number(args.number); console.log(number); renderCircle(number); }); };