Start on CommandRegistry

This commit is contained in:
Nathan Sobo
2014-09-05 08:22:28 -06:00
parent 04caea9bb0
commit decc983420
2 changed files with 51 additions and 0 deletions

View 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

View 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)