Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/webtorrent/webtorrent.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorFeross Aboukhadijeh <feross@feross.org>2016-04-21 11:47:01 +0300
committerFeross Aboukhadijeh <feross@feross.org>2016-04-21 11:47:01 +0300
commit0a22dc73c15eb9e74a3c0c13f570a76516e41799 (patch)
treefaca8b7df3bab2db600a21b02642fcb0f9198c0c /index.js
parent08baee2ddd7a194d44fc797e704b7a6b71304423 (diff)
client: cleanup event listeners
Diffstat (limited to 'index.js')
-rw-r--r--index.js21
1 files changed, 15 insertions, 6 deletions
diff --git a/index.js b/index.js
index de26366..60347cc 100644
--- a/index.js
+++ b/index.js
@@ -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
}