PROPOSAL: Use events instead of callbacks

What
--
Change the function signature of navigator.getUserMedia to return a 'NavigatorUserMedia' object that extends 'EventTarget' (fully specified in http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget) and eliminate the use of success and error callbacks:

	var media = navigator.getUserMedia({'video':true});
	media.addEventListener('onsuccess', function(Event e) { e.target.stream }, false);
	media.addEventListener('onerror', function(Event e) { e.target.error }, false);

Why
--
Events are preferred to callbacks in almost all WebAPIs in wide use today, examples include XHR and IndexedDB. Events are more flexible than callbacks as they allow multiple listeners, chaining, and bubbling; none of which are supported by a single callback (as currently specified in the specification). Some applications will not need the flexibility provided by Events, but it is trivial to emulate a single callback system built on top of events and is also a common idiom for web APIs:
	
	var media = navigator.getUserMedia({'audio':true});
	media.onsuccess = function(e) { e.target.stream; };

How
--
The function getUserMedia can be changed to return an object (the proposal calls it a 'NavigatorUserMedia' object) that extends 'EventTarget'. Event listeners can be added and removed using the standard event target methods. The 'Event' object passed to the onsuccess and onerror event listeners will have Event.target set to the 'UserMedia' object, which as the following two properties:
	
	NavigatorUserMedia.stream -> A MediaStream object assigned (null otherwise).
	NavigatorUserMedia.error -> A NavigatorUserMediaError object assigned (null otherwise).

I look forward to your feedback!

Regards,
-Anant

Received on Tuesday, 6 March 2012 19:38:53 UTC