diff --git a/docs/API.md b/docs/API.md index 5bad8c860e..e9fe058650 100644 --- a/docs/API.md +++ b/docs/API.md @@ -40,6 +40,7 @@ - [socket.emit(eventName[, ...args][, ack])](#socketemiteventname-args-ack) - [socket.on(eventName, callback)](#socketoneventname-callback) - [socket.join(room[, callback])](#socketjoinroom-callback) + - [socket.join(rooms[, callback])](#socketjoinrooms-callback) - [socket.leave(room[, callback])](#socketleaveroom-callback) - [socket.to(room)](#sockettoroom) - [socket.in(room)](#socketinroom) @@ -476,6 +477,14 @@ io.on('connection', function(client){ }); ``` +#### socket.join(rooms[, callback]) + + - `rooms` _(Array)_ + - `callback` _(Function)_ + - **Returns** `Socket` for chaining + +Adds the client to the list of room, and fires optionally a callback with `err` signature (if any). + #### socket.leave(room[, callback]) - `room` _(String)_ diff --git a/lib/socket.js b/lib/socket.js index 85911979ae..33158056f8 100644 --- a/lib/socket.js +++ b/lib/socket.js @@ -223,23 +223,31 @@ Socket.prototype.packet = function(packet, opts){ /** * Joins a room. * - * @param {String} room + * @param {String|Array} room or array of rooms * @param {Function} fn optional, callback * @return {Socket} self * @api private */ -Socket.prototype.join = function(room, fn){ - debug('joining room %s', room); +Socket.prototype.join = function(rooms, fn){ + debug('joining room %s', rooms); var self = this; - if (this.rooms.hasOwnProperty(room)) { + if (!Array.isArray(rooms)) { + rooms = [rooms]; + } + rooms = rooms.filter(function (room) { + return !self.rooms.hasOwnProperty(room); + }); + if (!rooms.length) { fn && fn(null); return this; } - this.adapter.add(this.id, room, function(err){ + this.adapter.addAll(this.id, rooms, function(err){ if (err) return fn && fn(err); - debug('joined room %s', room); - self.rooms[room] = room; + debug('joined room %s', rooms); + rooms.forEach(function (room) { + self.rooms[room] = room; + }); fn && fn(null); }); return this; diff --git a/package.json b/package.json index dc8f839f73..8030524ae3 100644 --- a/package.json +++ b/package.json @@ -28,7 +28,7 @@ "engine.io": "2.0.2", "has-binary": "0.1.7", "object-assign": "4.1.0", - "socket.io-adapter": "1.0.0", + "socket.io-adapter": "~1.1.0", "socket.io-client": "socketio/socket.io-client", "socket.io-parser": "2.3.1" }, diff --git a/test/socket.io.js b/test/socket.io.js index 3d87e3dba5..c683e6230d 100644 --- a/test/socket.io.js +++ b/test/socket.io.js @@ -2083,6 +2083,21 @@ describe('socket.io', function(){ }); }); }); + + it('allows to join several rooms at once', function(done) { + var srv = http(); + var sio = io(srv); + + srv.listen(function(){ + var socket = client(srv); + sio.on('connection', function(s){ + s.join(['a', 'b', 'c'], function(){ + expect(Object.keys(s.rooms)).to.eql([s.id, 'a', 'b', 'c']); + done(); + }); + }); + }); + }); }); describe('middleware', function(done){