谈谈 Vue 事件机制,手写$on,$off,$emit,$once
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | class Vue { constructor() { // 事件通道调度中心 this ._events = Object.create( null ); } $on(event, fn) { if (Array.isArray(event)) { event.map(item => { this .$on(item, fn); }); } else { ( this ._events[event] || ( this ._events[event] = [])).push(fn); } return this ; } $once(event, fn) { function on() { this .$off(event, on); fn.apply( this , arguments); } on.fn = fn; this .$on(event, on); return this ; } $off(event, fn) { if (!arguments.length) { this ._events = Object.create( null ); return this ; } if (Array.isArray(event)) { event.map(item => { this .$off(item, fn); }); return this ; } const cbs = this ._events[event]; if (!cbs) { return this ; } if (!fn) { this ._events[event] = null ; return this ; } let cb; let i = cbs.length; while (i--) { cb = cbs[i]; if (cb === fn || cb.fn === fn) { cbs.splice(i, 1); break ; } } return this ; } $emit(event) { let cbs = this ._events[event]; if (cbs) { const args = [].slice.call(arguments, 1); cbs.map(item => { args ? item.apply( this , args) : item.call( this ); }); } return this ; } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步