当前位置: 首页 > 科技观察

JavaScript迭代器模式和观察者模式

时间:2023-03-13 18:01:18 科技观察

迭代器模式介绍迭代器模式提供了一种在不暴露对象内部表示的情况下顺序访问聚合对象元素的方法。简单理解(白话解释):统一“集合”数据结构的遍历接口,实现循环遍历获取集合中的每一个数据项(不用关心数据项中的数据结构)生活栗子:listTodoList.每日清单包括学习、生活、工作、运动等项目,清单只是列出而已,与类别无关。模式特性为遍历不同数据结构的“集合”提供了统一的接口;它可以遍历和访问“集合”数据中的项目,并不关心项目的数据结构代码实现vareach=function(arr,callBack){for(leti=0,len=arr.length;i{handler(...params)})}//事件移除参数(事件名,删除的事件,如果没有第二个参数删除事件的订阅和发布)removeEventListener(type、手柄r){//抛出无效事件if(!(typeinthis.handlers)){returnnewError('invalidevent')}if(!handler){//直接移除事件deletethis.handlers[type]}else{constidx=this.handlers[type].findIndex(ele=>ele===handler)//抛出异常事件if(idx===undefined){returnnewError('Nosuchbindingevent')}//删除事件this.handlers[type].splice(idx,1)if(this.handlers[type].length===0){deletethis.handlers[type]}}}}varevent=newEvent()//创建一个事件实例//定义一个自定义事件:"load"functionload(params){console.log('load',params)}event.addEventListener('load',load)//然后定义一个加载事件functionload2(params){console.log('load2',params)}event.addEventListener('load',load2)//触发事件event.dispatchEvent('load','loadeventtrigger')//删除load2eventevent.removeEventListener('load',load2)//移除所有加载事件event.removeEventListener('加载')