locked
Clearing all event handlers from a silverlight object (SL 1.0) RRS feed

  • Question

  • In an effort to chase down circular references causing memory leaks I've been spending a lot of time removing event handlers from silverlight objects.  So far I can't find any good trick to just clear them all out instead of manually tracking the ids returned from AddEventHandler and all the events associated with the ids.  This is kind of a huge pain and is error prone. 

     Is there any trick to just clear out everything before nulling out the javascript reference to the object?

     

    Thanks,

    Ben

    Tuesday, June 3, 2008 6:29 PM

Answers

  • Oh, sorry, thought it was Silverlight 2... Unfortunately there's no easy way to clear event listeners in JavaScript. You'll have to track the token in AddEventListener, and pass the same token to RemoveEventListener one by one...

    Thursday, June 5, 2008 1:38 AM

All replies

  • Hello, is this what you want?

    public Page()

    {

    InitializeComponent();

    this.LayoutRoot.MouseLeftButtonDown += LayoutRoot_MouseLeftButtonDown;

    }

    void LayoutRoot_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)

    {

    HtmlPage.Window.Alert("abc");

    this.LayoutRoot.MouseLeftButtonDown -= LayoutRoot_MouseLeftButtonDown;

    }

    Click the root Grid, and you'll see the alert only once.

    Thursday, June 5, 2008 1:06 AM
  •  Are you sure you replied to the right post here?  That looks like C# code (this is a javascript question for Silverlight 1).  Also, I don't see how that clears all the event handlers on an object?

    Thursday, June 5, 2008 1:19 AM
  • Oh, sorry, thought it was Silverlight 2... Unfortunately there's no easy way to clear event listeners in JavaScript. You'll have to track the token in AddEventListener, and pass the same token to RemoveEventListener one by one...

    Thursday, June 5, 2008 1:38 AM
  •  Ouch - sure makes it easy to leak memory.  Thanks for the response!

    Thursday, June 5, 2008 1:48 AM