事件和DOM元素

Nic*_*ick 9 javascript jquery javascript-events

假设我有一个带有两列布局的页面,其中左列是一组链接,并且当单击该链接时,它会在右列中加载关联的html页面/模板.

在加载模板时,有一个模板处理程序,它通过requirejs初始化为单例,并定义了一些方法和处理程序,如:

SomePage.prototype.saveHandler: function(e) { ... }; // Page handler has a handler

SomePage.prototype.initialize: function() {
    $('#btnSave').on('click', saveHandler);
}
Run Code Online (Sandbox Code Playgroud)

然后,每次页面加载时,我都会通过初始化方法附加DOM事件.

SomePage.initialize(); // This attaches the click event
Run Code Online (Sandbox Code Playgroud)

现在,当我单击左侧的另一个链接时,将加载另一个模板页面,并为该页面重复上述过程.

我想知道之前附加到btnSave元素的click事件会发生什么?它现在是jQuery缓存中的悬空事件处理程序吗?

如果我再次加载同一页面时尝试删除它,它会实际删除原始事件吗?

$('#btnSave').off('click', saveHandler);
Run Code Online (Sandbox Code Playgroud)

执行以下块是否可以防止内存泄漏/悬空引用?

// The potential problem here is that btnSave is part of the newly loaded template 
// and not the element i attached the handler to earlier (which doesn't exist anymore)
$('#btnSave').off('click', saveHandler);

$('#btnSave').on('click', saveHandler); 
Run Code Online (Sandbox Code Playgroud)

什么是确保我最终没有悬挂引用和内存泄漏的最佳方法.这也是普通javascript的一个潜在问题.我的理解是,刷新模板页面时上述操作无效.我在同时试验它,但是知道专家如何处理它会很好.谢谢!

cbe*_*gni 0

当您加载新的 tmpl 时,您只需要附加事件即可。例如:

$("#btnSave", $(newly_tmpl)).on("点击",.....