diff --git a/lib/index.js b/lib/index.js index 8d2deb0..e939579 100644 --- a/lib/index.js +++ b/lib/index.js @@ -3,16 +3,67 @@ class Delegator { constructor (selector/* root选择器 */) { // TODO + this.root = document.querySelector(selector) + this.events = {} + this.delegator = e => { + var _event = e || window.event + var target = _event.target || _event.srcElement + var currentTarget = _event.currentTarget + + var _events = this.events[e.type] + + while (target !== currentTarget) { + _events.forEach(t => { + if (target.matches(t.selector)) { + var sTarget = target + t.callback.call(sTarget, e) + } + }) + + target = target.parentNode + } + } } on (event/* 绑定事件 */, selector/* 触发事件节点对应选择器 */, fn/* 出发函数 */) { // TODO + if (!Array.isArray(this.events[event])) { + this.events[event] = [] + } + + this.root.addEventListener(event, this.delegator, false) + + this.events[event].push({ + selector: selector, + callback: fn + }) + + return this } destroy () { // TODO + for (let type in this.events) { + this.root.removeEventListener(type, this.delegator, false); + } } } + // 处理 matches 的兼容性 + if (!Element.prototype.matches) { + Element.prototype.matches = + Element.prototype.matchesSelector || + Element.prototype.mozMatchesSelector || + Element.prototype.msMatchesSelector || + Element.prototype.oMatchesSelector || + Element.prototype.webkitMatchesSelector || + function(s) { + var matches = (this.document || this.ownerDocument).querySelectorAll(s), + i = matches.length + while (--i >= 0 && matches.item(i) !== this) {} + return i > -1 + } + } + root.Delegator = Delegator }(window, document) \ No newline at end of file diff --git a/package.json b/package.json index 89e61a0..c61cfe3 100644 --- a/package.json +++ b/package.json @@ -1,29 +1,29 @@ { - "name": "exercise20", - "version": "0.0.1", - "description": "test", - "main": "index.js", - "scripts": { - "test": "karma start" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/FE-star/exercise20.git" - }, - "keywords": [ - "test" - ], - "author": "Daniel Yang", - "license": "MIT", - "bugs": { - "url": "https://github.com/FE-star/exercise20/issues" - }, - "homepage": "https://github.com/FE-star/exercise20#readme", - "devDependencies": { - "karma": "^1.7.0", - "karma-chrome-launcher": "^1.0.1", - "karma-mocha": "^1.3.0", - "mocha": "^3.5.0", - "should": "^11.2.1" - } -} \ No newline at end of file + "name": "exercise20", + "version": "0.0.1", + "description": "test", + "main": "index.js", + "scripts": { + "test": "karma start" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/FE-star/exercise20.git" + }, + "keywords": [ + "test" + ], + "author": "Daniel Yang", + "license": "MIT", + "bugs": { + "url": "https://github.com/FE-star/exercise20/issues" + }, + "homepage": "https://github.com/FE-star/exercise20#readme", + "devDependencies": { + "karma": "^1.7.0", + "karma-chrome-launcher": "^1.0.1", + "karma-mocha": "^1.3.0", + "mocha": "^3.5.0", + "should": "^11.2.1" + } +}