Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Connection status callback #58

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions ws4redis/static/js/ws4redis.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ function WS4Redis(options, $) {
'use strict';
var opts, ws, deferred, timer, attempts = 1;
var heartbeat_interval = null, missed_heartbeats = 0;
var status_callback = null, connected = false;

if (this === undefined)
return new WS4Redis(options, $);
Expand All @@ -11,6 +12,8 @@ function WS4Redis(options, $) {
if ($ === undefined)
$ = jQuery;
opts = $.extend({ heartbeat_msg: null }, options);
if (opts.status_callback && typeof opts.status_callback === 'function')
status_callback = opts.status_callback;
connect(opts.uri);

function connect(uri) {
Expand Down Expand Up @@ -47,6 +50,9 @@ function WS4Redis(options, $) {
// new connection, reset attemps counter
attempts = 1;
deferred.resolve();
connected = true;
if (status_callback)
status_callback(true);
if (opts.heartbeat_msg && heartbeat_interval === null) {
missed_heartbeats = 0;
heartbeat_interval = setInterval(send_heartbeat, 5000);
Expand All @@ -55,6 +61,12 @@ function WS4Redis(options, $) {

function on_close(evt) {
console.log("Connection closed!");
// only call the callback if the status has changed (this event also
// fires when a connection attempt fails)
if (status_callback && connected) {
connected = false;
status_callback(false);
}
if (!timer) {
// try to reconnect
var interval = generateInteval(attempts);
Expand Down