mirror of
https://github.com/atom/atom.git
synced 2026-02-16 09:35:54 -05:00
Allow subscribers to unsubscribe on a per-object basis
This makes use of the new ES6 WeakMap feature, which allows for a hash map that's keyed by object.
This commit is contained in:
@@ -1,13 +1,28 @@
|
||||
_ = require 'underscore'
|
||||
|
||||
module.exports =
|
||||
subscribe: (eventEmitter, eventName, callback) ->
|
||||
eventEmitter.on eventName, callback
|
||||
@subscriptions ?= []
|
||||
@subscriptions.push(cancel: -> eventEmitter.off eventName, callback)
|
||||
@subscriptionsByObject ?= new WeakMap
|
||||
@subscriptionsByObject.set(eventEmitter, []) unless @subscriptionsByObject.has(eventEmitter)
|
||||
|
||||
subscription = cancel: -> eventEmitter.off eventName, callback
|
||||
@subscriptions.push(subscription)
|
||||
@subscriptionsByObject.get(eventEmitter).push(subscription)
|
||||
|
||||
subscribeToCommand: (view, eventName, callback) ->
|
||||
view.command eventName, callback
|
||||
@subscriptions ?= []
|
||||
@subscriptions.push(cancel: -> view.off eventName, callback)
|
||||
|
||||
unsubscribe: ->
|
||||
subscription.cancel() for subscription in @subscriptions ? []
|
||||
unsubscribe: (object) ->
|
||||
if object
|
||||
for subscription in @subscriptionsByObject?.get(object) ? []
|
||||
subscription.cancel()
|
||||
_.remove(@subscriptions, subscription)
|
||||
@subscriptionsByObject?.delete(object)
|
||||
else
|
||||
subscription.cancel() for subscription in @subscriptions ? []
|
||||
@subscriptions = null
|
||||
@subscriptionsByObject = null
|
||||
|
||||
Reference in New Issue
Block a user