简体   繁体   English

如果dom元素具有指向关闭的指针,那么如果我从页面中删除dom元素,是否会导致内存泄漏?

[英]If dom element has pointer to closure, will this lead to memory leak if I remove dom element from page?

For example code like this^ 例如这样的代码^

function test_mem(elm, data){
    var data_storage = data;

    function handle_input(event){
        console.log(data_storage);
    };

    function update_data(data) {
        data_storage = data;
    }

    function clear_events() {
        elm.removeEventListener('input', handle_input);
        elm.fnc_ptr = undefined;
    }

    if (elm.fnc_ptr !== undefined){
        elm.fnc_ptr.update_data(data);
    } else {
        elm.addEventListener('input', handle_input);

        elm.fnc_ptr = {
            'clear_events' : clear_events,
            'update_data' : update_data
        }
    }
}

var elm = document.getElementsByClassName('test-input')[0];
test_mem(elm, [1,2,3,54,5]);

will this closure lead to memory leak, if I delete elm from dom tree? 如果我从dom树中删除elm,这种关闭会导致内存泄漏吗? I think this code not lead to memory leak, but may be I lost sight of something. 我认为这段代码不会导致内存泄漏,但是可能是我没有看到某些东西。

While modern browsers will most certainly handle this, an arguably better way to associate data with an element is to an object that conforms to the Event Listener Interface . 虽然现代浏览器肯定会处理此问题,但是将数据与元素关联的一种更好的方法是符合事件监听器接口的对象。

This lets you bind an object as the event handler instead of a function. 这使您可以将对象而不是函数绑定为事件处理程序。 The requirement is that the object has a handleEvent() method. 要求是对象必须具有handleEvent()方法。 When the event occurs, the handleEvent() gets invoked with this pointing to the object you bound, which will hold the stored data. 当事件发生时, handleEvent()被调用与this指向您绑定的对象,这将保持存储的数据。

You can still access the element via event.currentTarget . 您仍然可以通过event.currentTarget访问该元素。

function TestMem(elm, data){
    this.data_storage = data;

    if (elm.has_handler !== undefined) {
        this.update_data(data);
    } else {
        elm.addEventListener('input', this);
        elm.has_handler = true;
    }
}

// Implement the Event Listener interface
TestMem.prototype.handleEvent = function(event) {
    if (event.type === "input") {
        this.handle_input(event);
    }
};

TestMem.prototype.handle_input = function(event) {
    console.log(this.data_storage);
};

TestMem.prototype.update_data = function(data) {
    this.data_storage = data;
};

TestMem.prototype.clear_events = function(event) {
    event.currentTarget.removeEventListener('input', this);
    this.has_handler = undefined;
}


var elm = document.getElementsByClassName('test-input')[0];

new TestMem(elm, [1,2,3,54,5]);

Now there's an association between the element and the object when the event happens, and there's no closure problems at all. 现在,事件发生时元素和对象之间就有关联,并且根本没有关闭问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM