mirror of
https://github.com/alchemy-fr/Phraseanet.git
synced 2025-10-11 12:03:14 +00:00
Add WS Connection object
This commit is contained in:
@@ -1,36 +1,71 @@
|
||||
define([
|
||||
"underscore"
|
||||
], function (_) {
|
||||
return function (options) {
|
||||
if (!"url" in options) {
|
||||
throw "You must set the websocket 'url'"
|
||||
}
|
||||
if (!"topic" in options) {
|
||||
throw "You must set the websocket 'topic'"
|
||||
}
|
||||
if (!"eventAggregator" in options) {
|
||||
throw "You must set an event aggregator"
|
||||
}
|
||||
"underscore",
|
||||
"backbone"
|
||||
], function (_, Backbone) {
|
||||
var instance;
|
||||
|
||||
var eventAggregator = options.eventAggregator;
|
||||
function init(url) {
|
||||
var activeSession = null;
|
||||
|
||||
return {
|
||||
run: function() {
|
||||
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(options.url, function (session) {
|
||||
eventAggregator.trigger("ws:connect", session);
|
||||
session.subscribe(options.topic, function (topic, msg) {
|
||||
// double encoded string
|
||||
var msg = JSON.parse(JSON.parse(msg));
|
||||
eventAggregator.trigger("ws:"+msg.event, msg, session);
|
||||
}
|
||||
);
|
||||
ab.connect(url, function (session) {
|
||||
$this.setSession(session);
|
||||
$this.trigger("ws:connect", activeSession);
|
||||
},
|
||||
function (code, reason) {
|
||||
eventAggregator.trigger("ws:session-gone", code,reason);
|
||||
$this.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;
|
||||
},
|
||||
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);
|
||||
}
|
||||
}
|
||||
}, Backbone.Events);
|
||||
}
|
||||
|
||||
return {
|
||||
getInstance: function(url) {
|
||||
if (!instance) {
|
||||
instance = init(url);
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
};
|
||||
});
|
||||
|
Reference in New Issue
Block a user