Jemt / Fit.UI

Fit.UI is a JavaScript based UI framework built on Object Oriented principles
http://fitui.org
GNU Lesser General Public License v3.0
19 stars 7 forks source link

Events: Memory leak for event handlers #155

Open FlowIT-JIT opened 2 years ago

FlowIT-JIT commented 2 years ago

Event handlers registered using Fit.Events.AddHandler(..) remains in memory unless explicitly removed using Fit.Events.RemoveHandler(..). That's because we allow handlers to be removed using an event ID returned from AddHandler(..), so we maintain an index that map IDs to elements and event handler functions. But obviously this comes with the major disadvantage that we must make sure to call Fit.Events.RemoveHandler(..) when an element is no longer needed. That's simply not acceptable as it prevents the browser's garbage collector from automatically cleaning up memory when DOM elements are no longer referenced.

Get rid of support for removing event handlers using an ID so we no longer keep references to elements and their event handler functions.

FlowIT-JIT commented 2 years ago

Check mutation observers as well - make sure they don't leak memory!

FlowIT-JIT commented 1 year ago

Managing event handlers is a pain. Let's create a simple EventManager that makes it easy to get rid of all handlers registered, without us having to keep references to DOM elements, event handler functions, and event names. This should replace the use of Fit.Events.AddHandler(..) and Fit.Events.RemoveHandler(..).

// Create EventManager
var em = new Fit.EventManager();

// Register a ton of events
em.Add(elm, "click", function(e) {});
em.Add(elm, "keydown", function(e) {});
em.Add(elm, "touchstart", function(e) {});

// Register event that can be removed by an ID
em.Add(elm, "scroll", { Passive: true, Id: "MyScrollHandler" }, function(e) {});

// Remove individual event handler by ID
em.Remove("MyScrollHandler");

// Remove all event handlers
em.RemoveAll();

Replace everything found using this regex search (enable case sensitivity): Fit\.Events\.(AddHandler|RemoveHandler|AddMutationObserver|RemoveMutationObserver)|\.on\w+ = \w