Skip to content

Commit

Permalink
Updated Jymin
Browse files Browse the repository at this point in the history
  • Loading branch information
zerious committed Jun 21, 2014
1 parent 4d8de66 commit 84125cb
Show file tree
Hide file tree
Showing 5 changed files with 132 additions and 22 deletions.
79 changes: 65 additions & 14 deletions beams-client.js
@@ -1,9 +1,9 @@
/**
* ____ ____ _ _ _ ___ ___ _ ____
* | __ ) ___ __ _ _ __ ___ ___ / ___| (_) ___ _ __ | |_ __ __/ _ \ / _ \ / |___ \
* | _ \ / _ \/ _` | '_ ` _ \/ __| | | | | |/ _ \ '_ \| __| \ \ / / | | | | | || | __) |
* | |_) | __/ (_| | | | | | \__ \ | |___| | | __/ | | | |_ \ V /| |_| | |_| || |/ __/
* |____/ \___|\__,_|_| |_| |_|___/ \____|_|_|\___|_| |_|\__| \_/ \___(_)___(_)_|_____|
* ____ ____ _ _ _ ___ ___ _ _ _
* | __ ) ___ __ _ _ __ ___ ___ / ___| (_) ___ _ __ | |_ __ __/ _ \ / _ \ / | || |
* | _ \ / _ \/ _` | '_ ` _ \/ __| | | | | |/ _ \ '_ \| __| \ \ / / | | | | | || | || |_
* | |_) | __/ (_| | | | | | \__ \ | |___| | | __/ | | | |_ \ V /| |_| | |_| || |__ _|
* |____/ \___|\__,_|_| |_| |_|___/ \____|_|_|\___|_| |_|\__| \_/ \___(_)___(_)_| |_|
*
*
* http://lighter.io/beams
Expand All @@ -24,6 +24,8 @@
* Empty handler.
*/
var doNothing = function () {};

// TODO: Enable multiple handlers using "bind" or perhaps middlewares.
var responseSuccessHandler = doNothing;
var responseFailureHandler = doNothing;

Expand Down Expand Up @@ -54,8 +56,13 @@ var getResponse = function (
}
var request = getXhr();
if (request) {
onFailure = onFailure || responseFailureHandler;
onSuccess = onSuccess || responseSuccessHandler;
request.onreadystatechange = function() {
if (request.readyState == 4) {
//+env:debug
log('[Jymin] Received response from "' + url + '". (' + getResponse._WAITING + ' in progress).');
//-env:debug
--getResponse._WAITING;
var status = request.status;
var isSuccess = (status == 200);
Expand All @@ -65,7 +72,6 @@ var getResponse = function (
var data = parse(request.responseText);
data._STATUS = status;
data._REQUEST = request;
data = data || {_ERROR: '_OFFLINE'};
callback(data);
}
};
Expand All @@ -74,7 +80,6 @@ var getResponse = function (
if (body) {
request.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
}
getResponse._WAITING = (getResponse._WAITING || 0) + 1;

// Record the original request URL.
request._URL = url;
Expand All @@ -87,7 +92,14 @@ var getResponse = function (
// Record the time the request was made.
request._TIME = getTime();

// Allow applications to back off when too many requests are in progress.
getResponse._WAITING = (getResponse._WAITING || 0) + 1;

//+env:debug
log('[Jymin] Sending request to "' + url + '". (' + getResponse._WAITING + ' in progress).');
//-env:debug
request.send(body || null);

}
return true;
};
Expand All @@ -108,6 +120,23 @@ var forEach = function (
}
};

/**
* Iterate over an array, and call a callback with (index, value), as in jQuery.each
*/
var each = function (
array, // Array: The array to iterate over.
callback // Function: The function to call on each item. `callback(item, index, array)`
) {
if (array) {
for (var index = 0, length = getLength(array); index < length; index++) {
var result = callback(index, array[index], array);
if (result === false) {
break;
}
}
}
};

/**
* Iterate over an object's keys, and call a function on each key value pair.
*/
Expand All @@ -125,6 +154,23 @@ var forIn = function (
}
};

/**
* Iterate over an object's keys, and call a function on each (value, key) pair.
*/
var forOf = function (
object, // Object*: The object to iterate over.
callback // Function*: The function to call on each pair. `callback(value, key, object)`
) {
if (object) {
for (var key in object) {
var result = callback(object[key], key, object);
if (result === false) {
break;
}
}
}
};

/**
* Decorate an object with properties from another object. If the properties
*/
Expand Down Expand Up @@ -623,7 +669,7 @@ var Beams = function () {
var hasRendered = false;
onReady(function () {
if (hasRendered) {
callbacks = {};
callbacks = {connect: onConnect};
}
hasRendered = true;
});
Expand Down Expand Up @@ -662,15 +708,15 @@ var Beams = function () {
* Listen for "connect" messages.
*/
Beams._CONNECT = Beams.connect = function (callback) {
this._ON('connect', callback);
Beams._ON('connect', callback);
return Beams;
};

/**
* Emit a message to the server via XHR POST.
*/
Beams._EMIT = Beams.emit = function (name, data) {
data = stringify(data || {}, 0, 1);
data = stringify(data || {}, 1);

//+env:debug
log('[Beams] Emitting "' + name + '": ' + data + '.');
Expand Down Expand Up @@ -707,7 +753,7 @@ var Beams = function () {
*/
function poll() {
//+env:debug
log('[Beams] Polling for messages.');
log('[Beams] Polling for messages at "' + endpointUrl + '".');
//-env:debug
getResponse(endpointUrl, onSuccess, onFailure);
}
Expand Down Expand Up @@ -751,16 +797,21 @@ var Beams = function () {
/**
* When we connect, set the client ID.
*/
Beams._CONNECT(function (data) {
decorateObject(Beams, data);
function onConnect(data) {
Beams.id = data.id;
endpointUrl = serverUrl + '?id=' + Beams.id;
//+env:debug
log('[Beams] Set endpoint URL to "' + endpointUrl + '".');
//-env:debug

// Now that we have the client ID, we can emit anything we had queued.
forEach(emissions, function (send) {
send();
});
emissions = [];
});
}

Beams._CONNECT(onConnect);

// Start polling.
poll();
Expand Down
2 changes: 1 addition & 1 deletion beams-client.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

63 changes: 61 additions & 2 deletions lib/Client.js
@@ -1,3 +1,62 @@
var reserved = /^(break|case|catch|continue|debugger|default|delete|do|else|finally|for|function|if|in|instanceof|new|return|switch|this|throw|try|typeof|var|void|while|with)$/;

/**
* Generate non-strict JSON that clients can eval.
*/
function stringify(data, stack) {
if (data === null) {
data = 'null';
}
else if (typeof data == 'function') {
data = ('' + data).replace(/^function \(/, 'function(');
}
else if (data instanceof Date) {
data = 'new Date(' + data.getTime() + ')';
}
else if (typeof data == 'object') {
stack = stack || [];
var isCircular = false;
stack.forEach(function (item, index) {
if (item == data) {
isCircular = true;
}
});
if (isCircular) {
return null;
}
stack.push(data);
var parts = [];
var before, after;
if (data instanceof Array) {
before = '[';
after = ']';
data.forEach(function (value) {
parts.push(stringify(value, stack));
});
}
else {
before = '{';
after = '}';
for (var key in data) {
if (reserved.test(key)) {
key = '"' + key + '"';
}
var value = data[key];
parts.push(key + ':' + stringify(value, stack));
}
}
stack.pop();
data = before + parts.join(',') + after;
}
else if (typeof data == 'string') {
data = '"' + data.replace(/"/g, '\\"') + '"';
}
else {
data = '' + data;
}
return data;
}

/**
* Create a new client.
*/
Expand All @@ -20,7 +79,7 @@ Client.prototype.resetTimeout = function () {
client.timeout = setTimeout(function () {
client.emit('timeout', duration);
}, duration);
}
};

/**
* Wait for messages.
Expand Down Expand Up @@ -48,7 +107,7 @@ Client.prototype.emit = function (name, data) {
// If there's a new emission, add it to the buffer.
if (name) {
this.buffer += (this.buffer ? ',' : '');
this.buffer += JSON.stringify([name, data]);
this.buffer += stringify([name, data]);
}
// If we can send the buffer, send it now.
// Otherwise, it will be sent when we reconnect.
Expand Down
8 changes: 4 additions & 4 deletions package.json
Expand Up @@ -15,7 +15,7 @@
"socket",
"io"
],
"version": "0.0.13",
"version": "0.0.14",
"main": "beams.js",
"homepage": "http://lighter.io/beams",
"repository": "git://github.com/zerious/beams.git",
Expand All @@ -35,16 +35,16 @@
"coveralls": "istanbul cover _mocha --report lcovonly -- -R spec && cat ./coverage/lcov.info | coveralls && rm -rf ./coverage"
},
"dependencies": {
"jymin": "0.2.6"
"jymin": "0.2.8"
},
"devDependencies": {
"assert-plus": "0.1.5",
"mocha": "1.20.1",
"istanbul": "0.2.11",
"express": "4.4.3",
"express": "4.4.4",
"zeriousify": "0.1.5",
"coveralls": "2.10.0",
"chug": "0.1.31",
"chug": "0.1.32",
"figlet": "1.0.9"
},
"bugs": {
Expand Down
2 changes: 1 addition & 1 deletion scripts/beams-jymin.js
Expand Up @@ -86,7 +86,7 @@ var Beams = function () {
* Emit a message to the server via XHR POST.
*/
Beams._EMIT = Beams.emit = function (name, data) {
data = stringify(data || {}, 0, 1);
data = stringify(data || {}, 1);

//+env:debug
log('[Beams] Emitting "' + name + '": ' + data + '.');
Expand Down

0 comments on commit 84125cb

Please sign in to comment.