Skip to content

Instantly share code, notes, and snippets.

@burg
Last active August 29, 2015 14:05
Show Gist options
  • Save burg/6a151fdf9abd7c62f544 to your computer and use it in GitHub Desktop.
Save burg/6a151fdf9abd7c62f544 to your computer and use it in GitHub Desktop.
Leakless promise API
WebInspector.EventListener = function(thisObject, fireOnce)
{
this._thisObject = thisObject;
this._emitter = null;
this._listener = null;
this._fireOnce = fireOnce;
}
WebInspector.EventListener.prototype = {
connect: function(emitter, type, listener, usesCapture)
{
console.assert(!this._emitter && !this._listener, "EventListener already bound.", this);
console.assert(listener, "Missing listener for event: " + type);
console.assert(emitter, "Missing event emitter for event: " + type);
console.assert(emitter instanceof WebInspector.Object || emitter instanceof Node || (typeof emitter.addEventListener === "function"), "Event emitter", emitter, " (type:" + type + ") does not implement Node or WebInspector.Object!");
this._emitter = emitter;
this._type = type;
this._usesCapture = usesCapture;
if (emitter instanceof Node)
listener = listener.bind(this._thisObject);
if (this._fireOnce) {
var receiver = this;
this._listener = function() {
receiver.disconnect();
listener(...arguments);
}
} else
this._listener = listener;
if (this._emitter instanceof Node)
this._emitter.addEventListener(this._type, this._listener, this._usesCapture);
else
this._emitter.addEventListener(this._type, this._listener, this._thisObject);
},
disconnect: function()
{
console.assert(this._emitter && this._listener, "EventListener is not bound.", this);
if (this._emitter instanceof Node)
this._emitter.removeEventListener(this._type, this._listener, this._usesCapture);
else
this._emitter.removeEventListener(this._type, this._listener, this._thisObject);
this._thisObject = null;
this._emitter = null;
this._type = null;
this._listener = null;
}
};
DebuggerManager.prototype = {
//...
pause: function()
{
if (this._paused)
return Promise.resolve();
listener = new WebInspector.EventListener(this, true);
var managerResult = new Promise(function(resolve, reject) {
listener.connect(WebInspector.debuggerManager, WebInspector.DebuggerManager.Event.Paused, resolve);
});
var protocolResult = DebuggerAgent.pause()
.catch(function(error) {
listener.disconnect();
console.error("DebuggerManager.pause failed: ", error);
throw error;
});
return new Promise.all([managerResult, protocolResult]);
},
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment