forked from kidozen/kido-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kido.pubsub.js
61 lines (43 loc) · 1.35 KB
/
kido.pubsub.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* access to the Pubsub backend service.
*
* @param kidoApp {object} - instance of the Kido class.
*/
var KidoPubsub = function ( kidoApp ) {
var self = this;
if (!(this instanceof KidoPubsub)) return new KidoPubsub(kidoApp);
if (!kidoApp) throw "The 'kidoApp' argument is required by the KidoPubsub class.";
this.app = kidoApp;
this.channel = function ( name ) {
return new KidoPubsubChannel(name, self.app);
};
};
var KidoPubsubChannel = function ( name, app ) {
var self = this;
this.name = name;
this.app = app;
this.publish = function ( data ) {
return self.app.send({
url: "/pubsub/" + self.app.name + "/" + self.name,
type: "POST",
data: JSON.stringify(data),
dataType: 'text'
});
};
this.subscribe = function ( cb ) {
var socket = io.connect('/pubsub');
socket.on('connect', function () {
socket.emit('bindToChannel', { application: self.app.name, channel: self.name });
});
socket.on('bindAccepted', function(m){
socket.on(m.responseChannelName, cb);
});
return function(){
socket.disconnect();
};
};
};
Kido.prototype.pubsub = function () {
if (!this._pubsub) this._pubsub = new KidoPubsub(this);
return this._pubsub;
};