我有一个我不明白的内存泄漏。我编写了一种机制来处理具有半自动解除绑定的事件,这应该可以让我轻松清理内存。但在一种情况下,清理不会发生(我使用 chrome 的“配置文件(内存堆)”来检查剩下的“EventHandler”实例)。我真的不明白为什么会这样。关闭有一些奇怪的东西......
function Bind(obj, f) {
return function() {
return f.apply(obj, arguments);
}
}
function EventHandler() {
this.listeners = new Object();
var _listenerID = 0;
this.addListener = function(e, obj, listener, specialDisplay) {
if (typeof(listener) === "function") {
var listenerID = ++_listenerID;
console.log("Events (" + (++EventHandler.All) + ", " + listenerID + ") ++" + e);
if (!this.listeners.hasOwnProperty(e)) {
this.listeners[e] = new Object();
}
this.listeners[e][listenerID] = listener;
if (obj != null && typeof(obj.removeListener) == "function") {
var deleteListenerID = obj.addListener("Delete", null, Bind(this, function() {
this.removeListener(e, listenerID);
obj.removeListener("Delete", deleteListenerID);
}));
}
return listenerID;
}
return null;
}
this.fire = function(e, obj) {
if (this.listeners.hasOwnProperty(e)) {
for(var i in this.listeners[e]) {
this.listeners[e][i](obj);
}
}
}
this.removeListener = function(e, listenerID) {
if (this.listeners.hasOwnProperty(e) && this.listeners[e].hasOwnProperty(listenerID)) {
delete this.listeners[e][listenerID];
console.log("Events (" + (--EventHandler.All) + ", " + listenerID + ") --" + e);
}
}
}
EventHandler.All = 0;
function Loader() {
}
Loader.files = new Object();
Loader.LoadImage = function(src, f) {
if (!Loader.files.hasOwnProperty(src)) {
var handler = new EventHandler();
console.log("Loading.... (" + src + ")");
Loader.files[src] = function(fnct) {
handler.addListener("ImageLoaded", handler, function(img) {
fnct(img);
});
}
handler.addListener("ImageLoaded", handler, function() {
Loader.files[src] = function(fnct) {
fnct(img);
}
});
var img = new Image();
$(img).load(function() {
console.log("Loaded.... (" + src + ")");
handler.fire("ImageLoaded", img);
handler.fire("Delete");
$(img).unbind('load');
});
img.src = src;
}
Loader.files[src](f);
}
Loader.LoadImage("http://serge.snakeman.be/Demo/house.jpg", function() { alert("ok"); });