From 73ca3e0cc292221ff59333ba161b0485247b160a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=B4=E9=87=8E=E5=BD=92=E8=B8=AA?= Date: Fri, 16 Nov 2018 01:07:55 +0800 Subject: [PATCH 1/2] emmm... --- lib/index.js | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/lib/index.js b/lib/index.js index 8d2deb0..4a11aaf 100644 --- a/lib/index.js +++ b/lib/index.js @@ -3,16 +3,47 @@ class Delegator { constructor (selector/* root选择器 */) { // TODO + this.stack = []; + this.root = document.querySelector(selector); + this.delegate = null; } on (event/* 绑定事件 */, selector/* 触发事件节点对应选择器 */, fn/* 出发函数 */) { // TODO + this.stack.push(fn) + + // 链式调用时,移除先前的on传入的出发函数 + if ( this.delegate != null ){ + this.root.removeEventListener(event, this.delegate) + } + // 查出满足selector的dom + this.delegate = (e) => { + var i = 0; + while (i < e.path.length) { + if(e.path[i].matches(selector)){ + // 后进先出 + this.stack.reverse().forEach(fn => { + fn.call(e.path[i], e) + }); + return 0; + } + i++; + } + } + this.root.addEventListener(event, this.delegate) + return this; } destroy () { // TODO + this.root.removeEventListener(event, this.delegate); + this.delegate = null; + this.stack = [] } - } + } root.Delegator = Delegator -}(window, document) \ No newline at end of file +}(window, document) + + + \ No newline at end of file From 567e60e87ad4aa97c92fd9568f6ff1d597529741 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=B4=E9=87=8E=E5=BD=92=E8=B8=AA?= <2472906920@qq.com> Date: Fri, 16 Nov 2018 18:34:22 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E8=AF=AF=E4=BC=9A=E4=BA=86=E9=93=BE?= =?UTF-8?q?=E5=BC=8F=E8=B0=83=E7=94=A8=E7=9A=84=E6=84=8F=E6=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/index.js | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/lib/index.js b/lib/index.js index 4a11aaf..98bd4a4 100644 --- a/lib/index.js +++ b/lib/index.js @@ -3,13 +3,16 @@ class Delegator { constructor (selector/* root选择器 */) { // TODO - this.stack = []; + this.stack = {}; this.root = document.querySelector(selector); this.delegate = null; } on (event/* 绑定事件 */, selector/* 触发事件节点对应选择器 */, fn/* 出发函数 */) { // TODO + if(this.stack[selector] === undefined) + this.stack[selector] = []; + this.stack.push(fn) // 链式调用时,移除先前的on传入的出发函数 @@ -20,12 +23,12 @@ this.delegate = (e) => { var i = 0; while (i < e.path.length) { - if(e.path[i].matches(selector)){ - // 后进先出 - this.stack.reverse().forEach(fn => { - fn.call(e.path[i], e) - }); - return 0; + for(let sel in this.stack){ + if(e.path[i].matches(sel)){ + this.stack[sel].forEach(fn => { + fn.call(e.path[i], e) + }); + } } i++; } @@ -38,7 +41,7 @@ // TODO this.root.removeEventListener(event, this.delegate); this.delegate = null; - this.stack = [] + this.stack = {} } }