>  기사  >  웹 프론트엔드  >  javascript 게시-구독 모델에 대한 자세한 설명(예제 포함)

javascript 게시-구독 모델에 대한 자세한 설명(예제 포함)

不言
不言앞으로
2018-10-26 15:39:003323검색

이 글은 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<len;i++) {
        // 直接调用arr[i],其this指向为undefined(严格模式下)
        // 因此用apply将this指向arr[i]
        // 数组shift函数取出第一个参数,将剩下的参数传入函数中
        arr[i].apply(arr[i],arguments)
    }
}

var ev = new Event()
ev.on('click',function(a) {  // 订阅
    console.log(a)
})

ev.emit('click',1)   // 发布

위 코드는 구독을 먼저 구현하고 다시 게시하세요. 직접 게시하면 오류가 보고됩니다. 먼저 게시한 다음 구독하려면 어떻게 해야 하나요?

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 게시-구독 모델에 대한 자세한 설명(예제 포함)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 github.io에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제