48 msdn magazine WinJS on Windows 8.1
Th ankfully, I can fi x this easily with only a few changes to my code.
Implementing the Dispose Pattern in WinJS
In WinJS 2.0, all of the WinJS controls implement a “dispose” pattern
to address the issue of memory leaks. Whenever a WinJS control
falls out of scope (for example, when the user navigates to another
page), WinJS cleans up all references to it. The control is marked
for disposal, meaning that the internal Garbage Collector knows
to release all the memory allocated to the object.
The dispose pattern in WinJS has three important character-
istics that a control must provide
in order to be properly disposed:
- The top-level container
DOM element must have the
CSS class “win-disposable.”
- The control’s class must
include a field called
_disposed that is initially
set to false. You can add this
member to a control (along
with the win-disposable CSS
class) by calling WinJS.Util-
ities.markDisposable.
- Th e JavaScript class that
defi nes the control must
expose a “dispose” method.
In the dispose method:
- All memory allocated
to objects associated
with the control needs
to be released.
- All event handlers need
to be detached from the
child DOM objects.
- All children of the
control must have their
dispose methods called.
Th e best way to do this
is by calling WinJS.Util-
ities.disposeSubTree on
the host element.
- All outstanding promises
that might be referenced
within the control need
to be canceled (by call-
ing the Promise.cancel
method and then nulling
the variable out).
So, in the constructor function
for SearchLOCControl.Control,
I add the following lines of code:
this._disposed = false;
WinJS.Utilities.addClass(element,
"win-disposable");
Next, inside the SearchLOC-
Control class defi nition (the call to
WinJS.Class.defi ne), I add a new instance member named dispose.
Here’s the code for the dispose method:
dispose: function () {
this._disposed = true;
this.searchQuery.winControl.removeEventListener("querysubmitted",
this.submitQuery);
WinJS.Utilities.disposeSubTree(this.element);
this.searchQuery = null;
this._element.winControl = null;
this._element = null;
}
Figure 10 Roots View After Implementing Dispose
Figure 9 Dominators View After Implementing Dispose