]> git.r.bdr.sh - rbdr/dotfiles/blob - atom/packages/vim-mode/node_modules/event-kit/README.md
Update vim plugins
[rbdr/dotfiles] / atom / packages / vim-mode / node_modules / event-kit / README.md
1 # event-kit
2
3 This is a simple library for implementing event subscription APIs.
4
5 ## Implementing Event Subscription APIs
6
7 ```coffee
8 {Emitter} = require 'event-kit'
9
10 class 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
27 In the example above, we implement `::onDidChangeName` on the user object, which
28 will register callbacks to be invoked whenever the user's name changes. To do
29 so, we make use of an internal `Emitter` instance. We use `::on` to subscribe
30 the given callback in `::onDidChangeName`, and `::emit` in `::setName` to notify
31 subscribers. Finally, when the `User` instance is destroyed we call `::dispose`
32 on 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.
37 To unsubscribe, simply call dispose on the returned object.
38
39 ```coffee
40 subscription = user.onDidChangeName (name) -> console.log("My name is #{name}")
41 # Later, to unsubscribe...
42 subscription.dispose()
43 ```
44
45 You can also use `CompositeDisposable` to combine disposable instances together.
46
47 ```coffee
48 {CompositeDisposable} = require 'event-kit'
49
50 subscriptions = new CompositeDisposable
51 subscriptions.add user1.onDidChangeName (name) -> console.log("User 1: #{name}")
52 subscriptions.add user2.onDidChangeName (name) -> console.log("User 2: #{name}")
53
54 # Later, to unsubscribe from *both*...
55 subscriptions.dispose()
56 ```
57
58 ## Creating Your Own Disposables
59
60 Disposables are convenient ways to represent a resource you will no longer
61 need at some point. You can instantiate a disposable with an action to take when
62 no longer needed.
63
64 ```coffee
65 {Disposable} = require 'event-kit'
66
67 disposable = new Disposable => @destroyResource()
68 ```