Skip to content

Commit

Permalink
Extract exported code into internal function and return new instance …
Browse files Browse the repository at this point in the history
…of it on delegate
  • Loading branch information
dmitrykuzmenkov committed Jan 6, 2016
1 parent bb64469 commit 452270e
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 30 deletions.
60 changes: 31 additions & 29 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
var match_selector = require('./match_selector.js');

var event_handler = function (root, listeners) {
return function (e) {
var DOMD = function (node) {
// 0 - bubbling, 1 - capturing
var listeners = [{}, {}];

var handler = function (e) {
var ret;
var target = e.target;

Expand Down Expand Up @@ -35,7 +38,7 @@ var event_handler = function (root, listeners) {
// Find triggered element cuz we can get child of it in e.target
while (target) {
for (var i in list) {
if (match_selector(root, target, list[i].selector)) {
if (match_selector(node, target, list[i].selector)) {
ret = list[i].callback(e, target);
break;
}
Expand All @@ -47,41 +50,40 @@ var event_handler = function (root, listeners) {
}
}

if (target === root) {
if (target === node) {
break;
}

target = target.parentElement;
}
};
};

module.exports = function (node) {
// 0 - bubbling, 1 - capturing
var listeners = [{}, {}];
this.on = function (event, selector, callback, use_capture) {
var map = listeners[use_capture ? 1 : 0];
if (!map[event]) {
map[event] = [];
node.addEventListener(event, handler, !!use_capture);
}

return {
on: function (event, selector, callback, use_capture) {
var map = listeners[use_capture ? 1 : 0];
if (!map[event]) {
map[event] = [];
node.addEventListener(event, event_handler(node, listeners), !!use_capture);
}
map[event].push({
selector: selector,
callback: callback
});
};

map[event].push({
selector: selector,
callback: callback
});
},

off: function (event, selector) {
listeners.forEach(function (map) {
for (var i in map[event] || []) {
if (map[event][i].selector === selector) {
map[event].splice(i, 1);
}
this.off = function (event, selector) {
listeners.forEach(function (map) {
for (var i in map[event] || []) {
if (map[event][i].selector === selector) {
map[event].splice(i, 1);
}
});
}
}
});
};

return this;
};

module.exports = function (node) {
return new DOMD(node);
};
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "domd",
"description": "Small dependency free DOM delegator",
"keywords": ["DOM", "delegate", "event", "handle", "domd"],
"version": "0.5.5",
"version": "0.7.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
Expand Down

0 comments on commit 452270e

Please sign in to comment.