Created
September 6, 2010 08:00
-
-
Save Gozala/566773 to your computer and use it in GitHub Desktop.
Demo code switch to EventEmitter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
diff --git a/packages/jetpack-core/lib/request.js b/packages/jetpack-core/lib/request.js | |
index 0ab2df2..b3d8541 100644 | |
--- a/packages/jetpack-core/lib/request.js | |
+++ b/packages/jetpack-core/lib/request.js | |
@@ -39,6 +39,16 @@ const xpcom = require("xpcom"); | |
const xhr = require("xhr"); | |
const errors = require("errors"); | |
const apiUtils = require("api-utils"); | |
+const { EventEmitter } = require("events"); | |
+// This very bad hack cause we return private API instead of public one. | |
+// This constructor nor instances returned may be shared outside this module | |
+// scope. | |
+const _EventEmitter.compose({ | |
+ constructor: function EventEmitter() { | |
+ // returns private api instead of public one | |
+ return this; | |
+ } | |
+}) | |
// Instead of creating a new validator for each request, just make one and reuse it. | |
const validator = new OptionsValidator({ | |
@@ -69,12 +79,15 @@ const REUSE_ERROR = "This request object has been used already. You must " + | |
exports.Request = apiUtils.publicConstructor(Request); | |
function Request(options) { | |
- const self = this; | |
+ const privateAPI = _EventEmitter(); | |
+ const self = privateAPI._public; | |
// request will hold the actual XHR object | |
let request; | |
let response; | |
options = validator.validateOptions(options); | |
+ // not sure if we're sticking with `on` or `addListener` | |
+ self.on('complete', options.onComplete); | |
// function to prep the request since it's the same between GET and POST | |
function makeRequest(mode) { | |
@@ -110,7 +123,9 @@ function Request(options) { | |
if (request.readyState == 4) { | |
response = new Response(request); | |
errors.catchAndLog(function () { | |
- options.onComplete.call(self); | |
+ // note that this won't be Request object instead we're passing it as | |
+ // an argument to listener | |
+ privateAPI._emit('complete', self); | |
})(); | |
} | |
} | |
@@ -120,7 +135,7 @@ function Request(options) { | |
} | |
// Map these setters/getters to the options | |
- ["url", "headers", "onComplete", "content", "contentType"].forEach(function (k) { | |
+ ["url", "headers", "content", "contentType"].forEach(function (k) { | |
this.__defineGetter__(k, function () options[k]); | |
this.__defineSetter__(k, function (v) { | |
// This will automatically rethrow errors from apiUtils.validateOptions. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment