3 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
7 (function (exports, io) {
13 exports.SocketNamespace = SocketNamespace;
16 * Socket namespace constructor.
22 function SocketNamespace (socket, name) {
24 this.name = name || '';
26 this.json = new Flag(this, 'json');
32 * Apply EventEmitter mixin.
35 io.util.mixin(SocketNamespace, io.EventEmitter);
38 * Copies emit since we override it
43 SocketNamespace.prototype.$emit = io.EventEmitter.prototype.emit;
46 * Creates a new namespace, by proxying the request to the socket. This
47 * allows us to use the synax as we do on the server.
52 SocketNamespace.prototype.of = function () {
53 return this.socket.of.apply(this.socket, arguments);
62 SocketNamespace.prototype.packet = function (packet) {
63 packet.endpoint = this.name;
64 this.socket.packet(packet);
75 SocketNamespace.prototype.send = function (data, fn) {
77 type: this.flags.json ? 'json' : 'message'
81 if ('function' == typeof fn) {
82 packet.id = ++this.ackPackets;
84 this.acks[packet.id] = fn;
87 return this.packet(packet);
96 SocketNamespace.prototype.emit = function (name) {
97 var args = Array.prototype.slice.call(arguments, 1)
98 , lastArg = args[args.length - 1]
104 if ('function' == typeof lastArg) {
105 packet.id = ++this.ackPackets;
107 this.acks[packet.id] = lastArg;
108 args = args.slice(0, args.length - 1);
113 return this.packet(packet);
117 * Disconnects the namespace
122 SocketNamespace.prototype.disconnect = function () {
123 if (this.name === '') {
124 this.socket.disconnect();
126 this.packet({ type: 'disconnect' });
127 this.$emit('disconnect');
139 SocketNamespace.prototype.onPacket = function (packet) {
145 , args: io.util.toArray(arguments)
150 switch (packet.type) {
152 this.$emit('connect');
156 if (this.name === '') {
157 this.socket.onDisconnect(packet.reason || 'booted');
159 this.$emit('disconnect', packet.reason);
165 var params = ['message', packet.data];
167 if (packet.ack == 'data') {
169 } else if (packet.ack) {
170 this.packet({ type: 'ack', ackId: packet.id });
173 this.$emit.apply(this, params);
177 var params = [packet.name].concat(packet.args);
179 if (packet.ack == 'data')
182 this.$emit.apply(this, params);
186 if (this.acks[packet.ackId]) {
187 this.acks[packet.ackId].apply(this, packet.args);
188 delete this.acks[packet.ackId];
194 this.socket.onError(packet);
196 if (packet.reason == 'unauthorized') {
197 this.$emit('connect_failed', packet.reason);
199 this.$emit('error', packet.reason);
212 function Flag (nsp, name) {
213 this.namespace = nsp;
223 Flag.prototype.send = function () {
224 this.namespace.flags[this.name] = true;
225 this.namespace.send.apply(this.namespace, arguments);
234 Flag.prototype.emit = function () {
235 this.namespace.flags[this.name] = true;
236 this.namespace.emit.apply(this.namespace, arguments);
240 'undefined' != typeof io ? io : module.exports
241 , 'undefined' != typeof io ? io : module.parent.exports