1

広範な調査中に、この問題を処理する多くの回避策を見てきました。(いくつかの良いリンクについては、この SO 投稿を参照してくださいattachEvent()。) 私の主な関心事は、IEでの使用に起因するメモリ リークの処理です。とにかく、私の研究のすべての後、私はこの回避策を見つけました:

// written by Dean Edwards, 2005
// with input from Tino Zijdel - crisp@xs4all.nl
// http://dean.edwards.name/weblog/2005/10/add-event/
function addEvent(element, type, handler)
{
    if (element.addEventListener)
        element.addEventListener(type, handler, false);
    else
    {
        if (!handler.$$guid) handler.$$guid = addEvent.guid++;
        if (!element.events) element.events = {};
        var handlers = element.events[type];
        if (!handlers)
        {
            handlers = element.events[type] = {};
            if (element['on' + type]) handlers[0] = element['on' + type];
            element['on' + type] = handleEvent;
        }

        handlers[handler.$$guid] = handler;
    }
}
addEvent.guid = 1;

function removeEvent(element, type, handler)
{
    if (element.removeEventListener)
        element.removeEventListener(type, handler, false);
    else if (element.events && element.events[type] && handler.$$guid)
        delete element.events[type][handler.$$guid];
}

function handleEvent(event)
{
    event = event || fixEvent(window.event);
    var returnValue = true;
    var handlers = this.events[event.type];

    for (var i in handlers)
    {
        if (!Object.prototype[i])
        {
            this.$$handler = handlers[i];
            if (this.$$handler(event) === false) returnValue = false;
        }
    }

    if (this.$$handler) this.$$handler = null;

    return returnValue;
}

function fixEvent(event)
{
    event.preventDefault = fixEvent.preventDefault;
    event.stopPropagation = fixEvent.stopPropagation;
    return event;
}
fixEvent.preventDefault = function()
{
    this.returnValue = false;
}
fixEvent.stopPropagation = function()
{
    this.cancelBubble = true;
}

// This little snippet fixes the problem that the onload attribute on the body-element will overwrite
// previous attached events on the window object for the onload event
if (!window.addEventListener)
{
    document.onreadystatechange = function()
    {
        if (window.onload && window.onload != handleEvent)
        {
            addEvent(window, 'load', window.onload);
            window.onload = handleEvent;
        }
    }
}​

いくつか質問があります。このコードを見つけるのは簡単ではなかったので、このコードを使用している人はあまりいないと思います。そのため、他の人はさまざまなコードを使用しており、コードに問題はないと私は信じています。これが事実である場合、私が投稿したこのコードはやり過ぎですか?

また、私の調査で、これに似た無数の回避策が見つかったことも心配しています。

if (el.addEventListener){  
  el.addEventListener('click', callback, false);   
} else if (el.attachEvent){  
  el.attachEvent('onclick', callback);  
} 

このコードは、IE によって引き起こされるメモリ リークを処理しません。それでは、私の質問に移りましょう:プレーンな JavaScript を使用して処理する最善/標準的な回避策は何attachEvent()ですか?それは IE でのメモリ リークですか?

4

0 に答える 0