]> git.r.bdr.sh - rbdr/dotfiles/blame - atom/packages/ex-mode/node_modules/event-kit/README.md
Updates git submodules
[rbdr/dotfiles] / atom / packages / ex-mode / node_modules / event-kit / README.md
CommitLineData
24c7594d
BB
1# event-kit
2
3This is a simple library for implementing event subscription APIs.
4
5## Implementing Event Subscription APIs
6
7```coffee
8{Emitter} = require 'event-kit'
9
10class User
11 constructor: ->
12 @emitter = new Emitter
13
14 onDidChangeName: (callback) ->
15 @emitter.on 'did-change-name', callback
16
17 setName: (name) ->
18 if name isnt @name
19 @name = name
20 @emitter.emit 'did-change-name', name
21 @name
22
23 destroy: ->
24 @emitter.dispose()
25```
26
27In the example above, we implement `::onDidChangeName` on the user object, which
28will register callbacks to be invoked whenever the user's name changes. To do
29so, we make use of an internal `Emitter` instance. We use `::on` to subscribe
30the given callback in `::onDidChangeName`, and `::emit` in `::setName` to notify
31subscribers. Finally, when the `User` instance is destroyed we call `::dispose`
32on the emitter to unsubscribe all subscribers.
33
34## Consuming Event Subscription APIs
35
36`Emitter::on` returns a `Disposable` instance, which has a `::dispose` method.
37To unsubscribe, simply call dispose on the returned object.
38
39```coffee
40subscription = user.onDidChangeName (name) -> console.log("My name is #{name}")
41# Later, to unsubscribe...
42subscription.dispose()
43```
44
45You can also use `CompositeDisposable` to combine disposable instances together.
46
47```coffee
48{CompositeDisposable} = require 'event-kit'
49
50subscriptions = new CompositeDisposable
51subscriptions.add user1.onDidChangeName (name) -> console.log("User 1: #{name}")
52subscriptions.add user2.onDidChangeName (name) -> console.log("User 2: #{name}")
53
54# Later, to unsubscribe from *both*...
55subscriptions.dispose()
56```
57
58## Creating Your Own Disposables
59
60Disposables are convenient ways to represent a resource you will no longer
61need at some point. You can instantiate a disposable with an action to take when
62no longer needed.
63
64```coffee
65{Disposable} = require 'event-kit'
66
67disposable = new Disposable => @destroyResource()
68```