Channel.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. var Emitter = require('./Emitter');
  2. var each = require('./each');
  3. var remove = require('./remove');
  4. var some = require('./some');
  5. exports = Emitter.extend({
  6. initialize: function Channel() {
  7. this._connections = [];
  8. this.callSuper(Emitter, 'initialize');
  9. },
  10. send: function(msg) {
  11. var _this = this;
  12. each(this._connections, function(connection) {
  13. connection.emit('message', msg, _this);
  14. });
  15. },
  16. connect: function(connection) {
  17. if (this.isConnected(connection)) {
  18. return;
  19. }
  20. this._connections.push(connection);
  21. connection.connect(this);
  22. },
  23. disconnect: function(connection) {
  24. if (!this.isConnected(connection)) {
  25. return;
  26. }
  27. remove(this._connections, function(item) {
  28. return item === connection;
  29. });
  30. connection.disconnect(this);
  31. },
  32. isConnected: function(connection) {
  33. if (connection === this) {
  34. throw new Error('Channel cannot be connected to itself.');
  35. }
  36. return some(this._connections, function(item) {
  37. return item === connection;
  38. });
  39. },
  40. destroy: function() {
  41. var _this2 = this;
  42. each(this._connections, function(connection) {
  43. _this2.disconnect(connection);
  44. });
  45. }
  46. });
  47. module.exports = exports;