您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

javascript发布订阅模式的详解(附示例)

2025/4/26 2:34:16发布14次查看
本篇文章给大家带来的内容是关于javascript发布订阅模式的详解(附示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
发布订阅模式
事件发布/订阅模式 (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发布订阅模式的详解(附示例)的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product