Dojo FAQ: How do you cleanly remove aspect handles?

By on August 19, 2013 11:55 am

In addition to a simple, consistent, cross-browser interface to DOM events, dojo/on provides for very convenient clean-up – the function returns a handle with a remove method that will un-register the event listener. Clean-up concerns are not limited to DOM events, so Dojo provides the same interface for dojo/aspect and dojo/topic.


HTML:

<button id="triggerClick" type="button">Trigger onClick</button>
<button id="removeHandles" type="button">Remove Handles</button>

JavaScript:

require([
	'dojo/on',
	'dojo/aspect',
	'dojo/topic'
], function (on, aspect, topic) {
	var demo = {
		onClick: function (event) {
			topic.publish('/demo/onClick', event);
		}
	};

	var onHandle = on('triggerClick', 'click', demo.onClick);

	var aspectHandle = aspect.after(demo, 'onClick', function () {
		console.log('demo.onClick completed');
	});

	var topicHandle = topic.subscribe('/demo/onClick', function () {
		console.log('/demo/onClick topic published');
	});

	on('removeHandles', 'click', function () {
		onHandle.remove();
		aspectHandle.remove();
		topicHandle.remove();
	});
});

Combining this with Dijit’s mechanism for clean-up is very powerful – when a Dijit widget is destroyed, it will remove any registered event handlers.

In Dojo 1.8+, Dijits based on dijit/_WidgetBase have an own method for “owning” event handlers. Owned handlers are un-registered when the widget is disposed of by calling its destroy method.

require([
	'dojo/_base/declare',
	'dojo/on',
	'dijit/_WidgetBase',
	'dijit/_TemplatedMixin'
], function (declare, on, _WidgetBase, _TemplatedMixin) {
	return declare([_WidgetBase, _TemplatedMixin], {
		templateString: '<div><button type="button" data-dojo-attach-point="button">Click Me</button></div>',
		postCreate: function () {
			this.inherited(arguments); 
			this.own(
				on(this.button, 'click', function () { 
					console.log('Clicked!'); 
				}) 
			); 
		} 
	}); 
});

In the above code we have skipped creating intermediate variables to hold references to the remove handles and simply called “on” directly in the parameter list to the “own” method. When the widget’s destroy method is called, the owned handlers will be removed.

As you can see, Dojo provides powerful and easy to use mechanisms for building safe, high performance applications.