dom-emitter

Manage the events of a DOM element

Dom Emitter

Manage the events of a DOM element.

  • stores all listeners making cleanup easy
  • one DOM binding per event type
  • intuitive delegation
  • emits proper DOM events
  • convenient method binding
  • efficient context binding (no fn.bind(this))
var body = new DomEmitter(document.body)
body.on('click', console.log)
body.emit('click', {x:50,y:112})
// => {type: 'click', x:50, y:112, ...} 

It is also has a simple system for inferring methods from the name of the event:

function Button () {
    this.view = document.createElement('button')
    this.events = new DomEmitter(this.view, this)
    this.events.on('click')
}
Button.prototype.onClick = console.log
new Button().events.emit('click', {x:50,y:112})
// => {type: 'click', x:50, y:112, ...} 

Delegation. leave a space then write a CSS query:

body.on('click > div.button') // infers "onClick" 

Will only be triggered if a click occurs within a direct child of document.body that has a tagName of "div" and a "button" class.

Naming delegated functions can be a bit tricky so sometimes its more readable to declare them in an object:

body.on({
    'click > div.button': console.log,
    'mousedown > div.button'function(e){
        e.delegate.style.backgroundColor = '#888'
    },
    'login'function(e){
        alert('Welcome!')
    }
})

With component

$ component install jkroso/dom-emitter

With npm

$ npm install jkroso/dom-emitter --save
var DomEmitter = require('dom-emitter')

Initialize a DomEmitter. If you provide a context then that will be the source of implies methods. It will also be this inside handlers.

new DomEmitter(document.body, {
  onClick: console.log  
})

Bind to type with optional method. When method is undefined it inferred from type. Delegation is can be specified in type

 events.on('click', 'onClick')
 events.on('click') // implies "onClick" 
 events.on('click', function (e) {})
 events.on('click .ok') // delegates to `.ok` 

Remove a single behavior

All the following are equivalent:

events.off('click', 'onClick')
events.off('click') // implies 'onClick' 
events.off('click', events.onClick)

Add listener but remove it after one call

Create a DOM event and send it down to the DomEmitter's target. Any data you pass will be merged with the event object

manager.emit('mousedown')
manager.emit('login', {user: user})
manager.emit('keydown', {key: 'enter'})

Remove all bound functions. Optionally limited to a certain topic

this.clear() // all 
this.clear('click') // just click handlers