SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Jul 2008
    Location
    Wheaton, IL
    Posts
    26
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Replacing HTML without memory leaks and redundant code

    Hello,

    I'm building a JavaScript-based calendar for a client that will require me to replace the page's HTML based on the user's input. For example, if the user clicks on a particular date, then the month/week calendar will be replaced with the day calendar.

    Needless to say, there are several event listeners involved. However, if I suddenly swap out the month calendar for a day calendar, does that mean that there are several event listeners in memory for elements that no longer exist? Or are those listeners destroyed when the elements are destroyed?

    Basically my question is, every time I swap out the HTML, do I have to detach all of the old events too?

    Thanks.

  2. #2
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    If you remove an element from the DOM, all event listeners are killed along with it.

    This is sometimes the only way to get rid of an event listener, especially when using addEventListener and anonymous functions.

    As long as you actually remove the elements from the DOM (via innerHTML or removeChild), then there is no need to faff about with removing event listeners.

  3. #3
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It's tidier to handle all the mouse events from a calendar in one place, rather than setting handlers on every possible target. If you have a table with 28-31 days visible in 42 table cells,
    just handle ALL events from the table. You can always read the text value of the target or srcElement, to get the date, and you can change every cell without needing to reassign the handlers.

    The same goes for div and span elements, but a table is an easy container for a month of days.

  4. #4
    SitePoint Enthusiast
    Join Date
    Jul 2008
    Location
    Wheaton, IL
    Posts
    26
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks, Raffles. I am using innerHTML to replace the elements, so I guess I don't have to worry about it too much.

    mrhoo, I am just using one listener for the table, and then using the event's target/srcElement property along with that target's ID/href/class/other property to determine which action to take.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •