This repository has been archived by the owner on Dec 15, 2022. It is now read-only.
/
composite-disposable.coffee
82 lines (73 loc) · 2.2 KB
/
composite-disposable.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
Disposable = null
# Essential: An object that aggregates multiple {Disposable} instances together
# into a single disposable, so they can all be disposed as a group.
#
# These are very useful when subscribing to multiple events.
#
# ## Examples
#
# ```coffee
# {CompositeDisposable} = require 'atom'
#
# class Something
# constructor: ->
# @disposables = new CompositeDisposable
# editor = atom.workspace.getActiveTextEditor()
# @disposables.add editor.onDidChange ->
# @disposables.add editor.onDidChangePath ->
#
# destroy: ->
# @disposables.dispose()
# ```
module.exports =
class CompositeDisposable
disposed: false
###
Section: Construction and Destruction
###
# Public: Construct an instance, optionally with one or more disposables
constructor: ->
@disposables = new Set
@add(disposable) for disposable in arguments
# Public: Dispose all disposables added to this composite disposable.
#
# If this object has already been disposed, this method has no effect.
dispose: ->
unless @disposed
@disposed = true
@disposables.forEach (disposable) ->
disposable.dispose()
@disposables = null
return
###
Section: Managing Disposables
###
# Public: Add disposables to be disposed when the composite is disposed.
#
# If this object has already been disposed, this method has no effect.
#
# * `...disposables` {Disposable} instances or any objects with `.dispose()`
# methods.
add: ->
unless @disposed
for disposable in arguments by 1
assertDisposable(disposable)
@disposables.add(disposable)
return
# Public: Remove a previously added disposable.
#
# * `disposable` {Disposable} instance or any object with a `.dispose()`
# method.
remove: (disposable) ->
@disposables.delete(disposable) unless @disposed
return
# Public: Clear all disposables. They will not be disposed by the next call
# to dispose.
clear: ->
@disposables.clear() unless @disposed
return
assertDisposable = (disposable) ->
Disposable ?= require './disposable'
unless Disposable.isDisposable(disposable)
throw new TypeError('Arguments to CompositeDisposable.add must have a .dispose() method')
return