diff --git a/index.html b/index.html index 8da9c8d..fde8984 100644 --- a/index.html +++ b/index.html @@ -6,6 +6,19 @@ Document - +
+ +
+ + \ No newline at end of file diff --git "a/\346\211\213\345\206\231\344\270\200\344\270\252delegate.js" "b/\346\211\213\345\206\231\344\270\200\344\270\252delegate.js" new file mode 100644 index 0000000..a36354d --- /dev/null +++ "b/\346\211\213\345\206\231\344\270\200\344\270\252delegate.js" @@ -0,0 +1,50 @@ +!function(win, doc) { + class Delegator { + constructor(selector) { + this.root = doc.querySelector(selector) + this.events = {} + } + on(event, target, fn) { + if(!this.events[event]) { + this.events[event] = [] + } + this.events[event].push({ + target, + cb:fn + }) + this.root.addEventListener(event, this._delegate) + return this + } + _delegate(e) { + let target = e.target || e.srcElement + let currentTarget = e.currentTarget + while(target !== currentTarget) { + this.eventsObj[e.type].forEach(item => { + //查找订阅事件者 + if(target.matches(item.selector)){ + //执行订阅事件者携带的函数 + item.callback.call(target,e); + } + }); + //往上冒泡 + target = target.parentNode; + } + } + } +}(window, document) + + +function delegate(element, eventType, selector, fn) { + element.addEventListener(eventType, (e) => { + let el = e.target; + while (!el.matches(selector)) { + if (element === el) { + el = null; + break; + } + el = el.parentNode; + } + el && fn.call(el, e, el); + }); + return element; +} \ No newline at end of file diff --git "a/\346\211\213\345\206\231\344\270\200\344\270\252event.js" "b/\346\211\213\345\206\231\344\270\200\344\270\252event.js" new file mode 100644 index 0000000..518fa13 --- /dev/null +++ "b/\346\211\213\345\206\231\344\270\200\344\270\252event.js" @@ -0,0 +1,46 @@ +class Event { + constructor() { + this._event = {} + } + on(type, cb) { + if(!this._event[type]) { + this._event[type] = [] + } + if(typeof cb === 'function') { + // console.log(cb.name) + const index = this._event[type].findIndex(item => item.name && item.name === cb.name) + // console.log(index) + if(index >= 0) { + this._event[type].splice(index, 1) + } + this._event[type].push(cb) + } + } + off(type, cb) { + if(!this._event[type]) return + const index = this._event[type].findIndex(item => item.name && item.name === cb.name) + if(index >= 0) { + this._event[type].splice(index, 1) + } + } + emit(type, ...args) { + if(!this._event[type]) return + this._event[type].forEach(cb => { + cb(...args) + }) + } +} + +let e = new Event() +const fn = (...data) => { + console.log(data) +} +e.on('click', fn) +e.on('click', fn) +e.on('click', fn) +e.on('click', (e) => {console.log(e)}) +e.on('click', () => {console.log(2)}) +// e.off('click', fn) +// e.off('click', () => {console.log(1)}) +console.log(e) +e.emit('click', 1111, 11) \ No newline at end of file