mirror of
https://github.com/atom/atom.git
synced 2026-01-23 13:58:08 -05:00
Start on CommandRegistry
This commit is contained in:
30
spec/command-registry-spec.coffee
Normal file
30
spec/command-registry-spec.coffee
Normal file
@@ -0,0 +1,30 @@
|
||||
CommandRegistry = require '../src/command-registry'
|
||||
|
||||
describe "CommandRegistry", ->
|
||||
[registry, parent, child, grandchild] = []
|
||||
|
||||
beforeEach ->
|
||||
parent = document.createElement("div")
|
||||
child = document.createElement("div")
|
||||
grandchild = document.createElement("div")
|
||||
parent.classList.add('parent')
|
||||
child.classList.add('child')
|
||||
grandchild.classList.add('grandchild')
|
||||
child.appendChild(grandchild)
|
||||
parent.appendChild(child)
|
||||
document.querySelector('#jasmine-content').appendChild(parent)
|
||||
|
||||
registry = new CommandRegistry(parent)
|
||||
|
||||
it "invokes callbacks with selectors matching the target", ->
|
||||
called = false
|
||||
registry.add 'command', '.grandchild', (event) ->
|
||||
expect(this).toBe grandchild
|
||||
expect(event.type).toBe 'command'
|
||||
expect(event.eventPhase).toBe Event.BUBBLING_PHASE
|
||||
expect(event.target).toBe grandchild
|
||||
expect(event.currentTarget).toBe grandchild
|
||||
called = true
|
||||
|
||||
grandchild.dispatchEvent(new CustomEvent('command', bubbles: true))
|
||||
expect(called).toBe true
|
||||
21
src/command-registry.coffee
Normal file
21
src/command-registry.coffee
Normal file
@@ -0,0 +1,21 @@
|
||||
module.exports =
|
||||
class CommandRegistry
|
||||
constructor: (@rootNode) ->
|
||||
@listenersByCommandName = {}
|
||||
|
||||
add: (commandName, selector, callback) ->
|
||||
unless @listenersByCommandName[commandName]?
|
||||
@rootNode.addEventListener(commandName, @dispatchCommand, true)
|
||||
@listenersByCommandName[commandName] = []
|
||||
|
||||
@listenersByCommandName[commandName].push({selector, callback})
|
||||
|
||||
dispatchCommand: (event) =>
|
||||
syntheticEvent = Object.create event,
|
||||
eventPhase: value: Event.BUBBLING_PHASE
|
||||
currentTarget: get: -> currentTarget
|
||||
|
||||
currentTarget = event.target
|
||||
for listener in @listenersByCommandName[event.type]
|
||||
if event.target.webkitMatchesSelector(listener.selector)
|
||||
listener.callback.call(currentTarget, syntheticEvent)
|
||||
Reference in New Issue
Block a user