Allow listeners to be removed via a Disposable returned from ::add

This commit is contained in:
Nathan Sobo
2014-09-05 09:19:59 -06:00
parent fe27ebec1b
commit 4de0865d28
2 changed files with 25 additions and 1 deletions

View File

@@ -77,3 +77,18 @@ describe "CommandRegistry", ->
grandchild.dispatchEvent(new CustomEvent('command', bubbles: true))
expect(calls).toEqual ['child-1']
it "allows listeners to be removed via a disposable returned by ::add", ->
calls = []
disposable1 = registry.add 'command', '.parent', -> calls.push('parent')
disposable2 = registry.add 'command', '.child', -> calls.push('child')
disposable1.dispose()
grandchild.dispatchEvent(new CustomEvent('command', bubbles: true))
expect(calls).toEqual ['child']
calls = []
disposable2.dispose()
grandchild.dispatchEvent(new CustomEvent('command', bubbles: true))
expect(calls).toEqual []

View File

@@ -1,3 +1,4 @@
{Disposable} = require 'event-kit'
{specificity} = require 'clear-cut'
SequenceCount = 0
@@ -13,7 +14,15 @@ class CommandRegistry
@rootNode.addEventListener(commandName, @dispatchCommand, true)
@listenersByCommandName[commandName] = []
@listenersByCommandName[commandName].push(new CommandListener(selector, callback))
listener = new CommandListener(selector, callback)
listenersForCommand = @listenersByCommandName[commandName]
listenersForCommand.push(listener)
new Disposable =>
listenersForCommand.splice(listenersForCommand.indexOf(listener), 1)
if listenersForCommand.length is 0
delete @listenersByCommandName[commandName]
@rootNode.removeEventListener(commandName, @dispatchCommand, true)
dispatchCommand: (event) =>
propagationStopped = false