diff options
author | Feross Aboukhadijeh <feross@feross.org> | 2016-04-21 11:47:01 +0300 |
---|---|---|
committer | Feross Aboukhadijeh <feross@feross.org> | 2016-04-21 11:47:01 +0300 |
commit | 0a22dc73c15eb9e74a3c0c13f570a76516e41799 (patch) | |
tree | faca8b7df3bab2db600a21b02642fcb0f9198c0c /index.js | |
parent | 08baee2ddd7a194d44fc797e704b7a6b71304423 (diff) |
client: cleanup event listeners
Diffstat (limited to 'index.js')
-rw-r--r-- | index.js | 21 |
1 files changed, 15 insertions, 6 deletions
@@ -1,5 +1,3 @@ -// TODO: cleanup event listeners - module.exports = WebTorrent var createTorrent = require('create-torrent') @@ -92,9 +90,11 @@ function WebTorrent (opts) { if (opts.dht !== false && typeof DHT === 'function' /* browser exclude */) { // use a single DHT instance for all torrents, so the routing table can be reused self.dht = new DHT(extend({ nodeId: self.nodeId }, opts.dht)) + self.dht.once('error', function (err) { self._destroy(err) }) + self.dht.once('listening', function () { var address = self.dht.address() if (address) self.dhtPort = address.port @@ -219,24 +219,33 @@ WebTorrent.prototype.add = function (torrentId, opts, ontorrent) { var torrent = new Torrent(torrentId, self, opts) self.torrents.push(torrent) - torrent.once('infoHash', function () { + torrent.once('infoHash', onInfoHash) + torrent.once('ready', onReady) + torrent.once('close', onClose) + + function onInfoHash () { if (self.destroyed) return for (var i = 0, len = self.torrents.length; i < len; i++) { var t = self.torrents[i] if (t.infoHash === torrent.infoHash && t !== torrent) { - torrent.removeListener('ready', onReady) torrent._destroy(new Error('Cannot add duplicate torrent ' + torrent.infoHash)) return } } - }) - torrent.once('ready', onReady) + } function onReady () { + if (self.destroyed) return if (typeof ontorrent === 'function') ontorrent(torrent) self.emit('torrent', torrent) } + function onClose () { + torrent.removeListener('infoHash', onInfoHash) + torrent.removeListener('ready', onReady) + torrent.removeListener('close', onClose) + } + return torrent } |