WSConnection is not a singleton anymore

This commit is contained in:
Nicolas Le Goff
2014-02-27 14:25:10 +01:00
parent 5216e8fc9c
commit ef5b3fadb7
3 changed files with 59 additions and 75 deletions

View File

@@ -2,70 +2,52 @@ define([
"underscore",
"backbone"
], function (_, Backbone) {
var instance;
var activeSession = null;
function init(url) {
var activeSession = null;
return _.extend({
connect: function() {
if (this.hasSession()) {
return;
}
var $this = this;
// autobahn js is defined as a global object there is no way to load
// it as a UMD module
ab.connect(url, function (session) {
$this.setSession(session);
$this.trigger("ws:connect", activeSession);
},
function (code, reason) {
$this.trigger("ws:session-gone", code, reason);
return _.extend({
connect: function(url) {
if (this.hasSession()) {
throw "Connection is already active";
}
var that = this;
// autobahn js is defined as a global object there is no way to load
// it as a UMD module
ab.connect(url, function (session) {
that.setSession(session);
that.trigger("ws:connect", activeSession);
},
function (code, reason) {
that.trigger("ws:session-gone", code, reason);
});
},
close: function() {
if (false === this.hasSession()) {
return;
}
this.getSession().close();
this.setSession(null);
this.trigger("ws:session-close");
},
hasSession: function() {
return this.getSession() !== null;
},
subscribe: function(topic, callback) {
if (false === this.hasSession()) {
this.on("ws:connect", function(session) {
session.subscribe(topic, callback);
this.trigger("ws:session-subscribe", topic);
});
},
close: function() {
if (false === this.hasSession()) {
return;
}
this.getSession().close();
this.setSession(null);
this.trigger("ws:session-close");
},
hasSession: function() {
return this.getSession() !== null;
},
getSession: function() {
return activeSession;
},
setSession: function(session) {
activeSession = session;
},
subscribe: function(topic, callback) {
if (false === this.hasSession()) {
this.on("ws:connect", function(session) {
session.subscribe(topic, callback);
});
return;
}
this.getSession().subscribe(topic, callback);
this.trigger("ws:session-subscribe", topic);
},
unsubscribe: function(topic, callback) {
if (false === this.hasSession()) {
return;
}
this.getSession().unsubscribe(topic, callback);
this.trigger("ws:session-unsubscribe", topic);
return;
}
}, Backbone.Events);
}
return {
getInstance: function(url) {
if (!instance) {
instance = init(url);
this.getSession().subscribe(topic, callback);
this.trigger("ws:session-subscribe", topic);
},
unsubscribe: function(topic, callback) {
if (false === this.hasSession()) {
return;
}
return instance;
this.getSession().unsubscribe(topic, callback);
this.trigger("ws:session-unsubscribe", topic);
}
};
}, Backbone.Events);
});