W3C home > Mailing lists > Public > public-media-capture@w3.org > March 2012

PROPOSAL: Use events instead of callbacks

From: Anant Narayanan <anant@mozilla.com>
Date: Tue, 6 Mar 2012 11:38:18 -0800
Message-Id: <C90479C6-4B66-4874-8AA7-7FC166DE04B7@mozilla.com>
To: public-media-capture@w3.org
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);

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; };

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!

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

This archive was generated by hypermail 2.4.0 : Friday, 17 January 2020 16:26:09 UTC