Skip to content

Commit a3cbc84

Browse files
[feat] Make of return a new Emitter instance (#56)
1 parent 119b3e6 commit a3cbc84

File tree

1 file changed

+20
-24
lines changed

1 file changed

+20
-24
lines changed

index.js

Lines changed: 20 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ var debug = require('debug')('socket.io-emitter');
1212
* Module exports.
1313
*/
1414

15-
module.exports = Emitter;
15+
module.exports = init;
1616

1717
/**
1818
* Flags.
@@ -42,8 +42,7 @@ var uid = 'emitter';
4242
* @api public
4343
*/
4444

45-
function Emitter(redis, opts){
46-
if (!(this instanceof Emitter)) return new Emitter(redis, opts);
45+
function init(redis, opts){
4746
opts = opts || {};
4847

4948
if ('string' == typeof redis) {
@@ -63,8 +62,16 @@ function Emitter(redis, opts){
6362
: client(opts.port, opts.host);
6463
}
6564

65+
var prefix = opts.key || 'socket.io';
66+
67+
return new Emitter(redis, prefix, '/');
68+
}
69+
70+
function Emitter(redis, prefix, nsp){
6671
this.redis = redis;
67-
this.prefix = (opts.key || 'socket.io');
72+
this.prefix = prefix;
73+
this.nsp = nsp;
74+
this.channel = this.prefix + '#' + nsp + '#';
6875

6976
this._rooms = [];
7077
this._flags = {};
@@ -98,15 +105,13 @@ Emitter.prototype.to = function(room){
98105
};
99106

100107
/**
101-
* Limit emission to certain `namespace`.
108+
* Return a new emitter for the given namespace.
102109
*
103110
* @param {String} namespace
104111
*/
105112

106-
Emitter.prototype.of = function(nsp) {
107-
debug('nsp set to %s', nsp);
108-
this._flags.nsp = nsp;
109-
return this;
113+
Emitter.prototype.of = function(nsp){
114+
return new Emitter(this.redis, this.prefix, nsp);
110115
};
111116

112117
/**
@@ -118,29 +123,20 @@ Emitter.prototype.of = function(nsp) {
118123
Emitter.prototype.emit = function(){
119124
// packet
120125
var args = Array.prototype.slice.call(arguments);
121-
var packet = { type: parser.EVENT, data: args };
122-
123-
// set namespace to packet
124-
if (this._flags.nsp) {
125-
packet.nsp = this._flags.nsp;
126-
delete this._flags.nsp;
127-
} else {
128-
packet.nsp = '/';
129-
}
126+
var packet = { type: parser.EVENT, data: args, nsp: this.nsp };
130127

131128
var opts = {
132129
rooms: this._rooms,
133130
flags: this._flags
134131
};
135-
var chn = this.prefix + '#' + packet.nsp + '#';
136-
var msg = msgpack.encode([uid, packet, opts]);
137132

138-
// publish
133+
var msg = msgpack.encode([uid, packet, opts]);
134+
var channel = this.channel;
139135
if (opts.rooms && opts.rooms.length === 1) {
140-
this.redis.publish(chn + opts.rooms[0], msg);
141-
} else {
142-
this.redis.publish(chn, msg);
136+
channel += opts.rooms[0] + '#';
143137
}
138+
debug('publishing message to channel %s', channel);
139+
this.redis.publish(channel, msg);
144140

145141
// reset state
146142
this._rooms = [];

0 commit comments

Comments
 (0)