发布订阅模式
事件发布/订阅模式 (pubsub) 在异步编程中帮助我们完成更松的解耦,甚至在 mvc、mvvc 的架构中以及设计模式中也少不了发布-订阅模式的参与。
优点:在异步编程中实现更深的解耦
缺点:如果过多的使用发布订阅模式,会增加维护的难度
实现发布订阅模式
var event = function() { this.obj = {}}event.prototype.on = function(eventtype,fn) { if(!this.obj[eventtype]) { this.obj[eventtype] = [] } this.obj[eventtype].push(fn)}event.prototype.emit = function() { // 取第一个参数,作为eventtype var eventtype = array.prototype.shift.call(arguments); // 获取事件数组 var arr = this.obj[eventtype]; var len = arr.length; // 循环数组,一次执行其中的函数 for(var i=0;i
var event = function() { this.obj = {}; this.cachelist = [];}event.prototype.emit = function() { const args = arguments; //函数参数 const that = this; //this指向,保持cache函数的this指向 function cache() { var eventtype = array.prototype.shift.call(arg) var arr = that.obj[eventtype] for (let i = 0; i < arr.length; i++) { arr[i].apply(arr[i], arg) } } this.cachelist.push(cache) // 采用闭包,保持对emit函数中参数和that的引用}event.prototype.on = function(eventtype,fn) { if(!this.obj[eventtype]) { this.obj[eventtype] = [] } this.obj[eventtype].push(fn) // 在订阅函数中执行emit函数中缓存的函数 for (let i = 0; i < this.cachelist.length; i++) { this.cachelist[i]() }}
改成这样后就实现了先发布函数,再订阅的过程。但是也只能先发布,然后再订阅,反过来就行不通。
以上就是javascript发布订阅模式的详解(附示例)的详细内容。
