Replaces every single event listener in favor of event delegation

This commit is contained in:
Zeno Rocha 2015-09-24 17:02:33 -07:00
parent 540038e2ad
commit ced945f11a
4 changed files with 16 additions and 47 deletions

File diff suppressed because one or more lines are too long

View File

@ -9,7 +9,8 @@
"cut"
],
"dependencies": {
"custom-event": "^1.0.0"
"custom-event": "^1.0.0",
"delegate-events": "^1.1.1"
},
"devDependencies": {
"babelify": "^6.3.0",

View File

@ -1,26 +1,20 @@
var ClipboardAction = require('./clipboard-action');
var Delegate = require('dom-delegate').Delegate;
/**
* Base class which takes a selector, binds a click event for
* each element found, and instantiates a new `ClipboardAction`.
* Base class which takes a selector, delegates a click event to it,
* and instantiates a new `ClipboardAction` on each click.
*/
class Clipboard {
/**
* Fetches all elements from a selector and
* calls `bind` method for each element found.
* @param {String} triggers
* Delegates a click event to the passed selector.
* @param {String} selector
*/
constructor(triggers) {
this.triggers = document.querySelectorAll(triggers);
constructor(selector) {
this.selector = selector;
[].forEach.call(this.triggers, (trigger) => this.bind(trigger));
}
/**
* Adds a click event listener for each element.
*/
bind(trigger) {
trigger.addEventListener('click', (e) => this.initialize(e));
let delegate = new Delegate(document.body);
delegate.on('click', this.selector, (e) => this.initialize(e));
}
/**
@ -29,33 +23,12 @@ class Clipboard {
*/
initialize(e) {
new ClipboardAction({
action : e.currentTarget.getAttribute('data-action'),
target : e.currentTarget.getAttribute('data-target'),
text : e.currentTarget.getAttribute('data-text'),
trigger : e.currentTarget
action : e.target.getAttribute('data-action'),
target : e.target.getAttribute('data-target'),
text : e.target.getAttribute('data-text'),
trigger : e.target
});
}
/**
* Sets the `triggers` property if there's at least
* one match for the provided selector.
* @param {NodeList} triggers
*/
set triggers(triggers) {
if (!triggers.length) {
throw new Error('No matches were found for the provided selector');
}
this._triggers = triggers;
}
/**
* Gets the `triggers` property.
* @return {NodeList}
*/
get triggers() {
return this._triggers;
}
}
export default Clipboard;

View File

@ -25,11 +25,6 @@ describe('Clipboard', () => {
done();
}
});
it('should create a NodeList from selector and store it in a "triggers" property', () => {
let clipboard = new Clipboard('.btn');
return assert.instanceOf(clipboard.triggers, NodeList);
});
});
after(() => {