在javascript中我们习惯用
object.attachEvent("OnDisConnected", DisConnected);
这样的方式来绑定组件触发OnDisConnected事件的处理方法,DisConnected。
但是有一点,这样写的话要在页面的onunload事件中就需要对其进行卸载--detachEvent。
否则这个过程就会一直驻留在内存中。有可能会导致内存泄露。
These handlers will stay in RAM, filling it up slowly, clogging the browser’s arteries. This is known as a memory leak.(Protytype中的解释)。
Prototype对绑定事件进行了封装。
Event.observe(object, 'DisConnected',DisConnected);
observe:
function
(element, name, observer, useCapture)
...
{
element = $(element);
useCapture = useCapture || false;
if (name == 'keypress' &&
(Prototype.Browser.WebKit || element.attachEvent))
name = 'keydown';
Event._observeAndCache(element, name, observer, useCapture);
} ,
element = $(element);
useCapture = useCapture || false;
if (name == 'keypress' &&
(Prototype.Browser.WebKit || element.attachEvent))
name = 'keydown';
Event._observeAndCache(element, name, observer, useCapture);
} ,
这样,prototype就会自己来处理卸载绑定。
unloadCache: function () ... {
if (!Event.observers) return;
for (var i = 0, length = Event.observers.length; i < length; i++) ...{
Event.stopObserving.apply(this, Event.observers[i]);
Event.observers[i][0] = null;
}
Event.observers = false;
} ,
当页面unload时就会从内存中将其卸载。
What’s even better is, Prototype automatically hooks unloadCache to page unloading, exclusively for MSIE. So you don’t have anything to do.