3 This is a simple library for implementing event subscription APIs.
5 ## Implementing Event Subscription APIs
8 {Emitter} = require 'event-kit'
12 @emitter = new Emitter
14 onDidChangeName: (callback) ->
15 @emitter.on 'did-change-name', callback
20 @emitter.emit 'did-change-name', name
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.
34 ## Consuming Event Subscription APIs
36 `Emitter::on` returns a `Disposable` instance, which has a `::dispose` method.
37 To unsubscribe, simply call dispose on the returned object.
40 subscription = user.onDidChangeName (name) -> console.log("My name is #{name}")
41 # Later, to unsubscribe...
42 subscription.dispose()
45 You can also use `CompositeDisposable` to combine disposable instances together.
48 {CompositeDisposable} = require 'event-kit'
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}")
54 # Later, to unsubscribe from *both*...
55 subscriptions.dispose()
58 ## Creating Your Own Disposables
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
65 {Disposable} = require 'event-kit'
67 disposable = new Disposable => @destroyResource()