비동기 노드 ---> 시뮬레이션 이벤트

행사

  • 가장 일반적인에서 대화 형 이벤트 브라우저의 첫 페이지입니다
  • 그것은 게시 / 디자인 패턴을 구독 본질적으로

  • 사용하여 객체 add이벤트를 구독하는 방법.
  • 사용 emit후 메시지를

이벤트에 가입

  • 해당 처리 기능뿐만 아니라, 트리거 이벤트의 고유 한 문자열을 추가
  • 초기화 이벤트 객체
class Event {
	constructor(){
		this.events = {};
	}
}
  • 신청
  • 시간의 이벤트에 가입, 우리는 이벤트가 있는지 여부를 결정해야합니다.
  • 그렇지 않다면, 직접 큐로 (어레이)
  • 존재하는 경우, 꼬리를 넣어 (푸시가 들어갑니다)
class Event {
	constructor(){...},
	add(name, cb) {
		if (this.map[name]) {
			this.map[name].push(fn);
			return;
		}
		this.map[name] = [fn];
		return;
	}
}

게시 이벤트

  • 사용하는 경우 emit방법을 첫 번째 인수는 이벤트의 이름이다.
  • emit방법은 수신 이름에 기초 할 것이며, 대응하는 이벤트 처리 그룹을 찾아.
  • 차례 호출의 매개 변수의 뒷면에 이벤트 처리 그룹
class Event {
	constructor(){ ... }
	emit(name, ...args) {
		this.map[name].forEach( cb => {
			cb(...args);
		})
	}
}

전화

const e = new Event();
e.add('sayHello', (err, name) =>{
	if(err) {
		console.error(err);
		return
	}
	console.log(`hello ${name}`);
	return
})
e.emit('sayHello','发生了错误');
e.emit('sayHello', null, 'marron');

그림 삽입 설명 여기


체인 호출을 달성

  • 나는 전화를하는 방법으로 사용하려면
const e = new Event();
e
.add('sayHello', (err, name) =>{
	if(err) {
		console.error(err);
		return;
	}
	console.log(`hello ${name}`);
})
.emit('sayHello', '发生了错误')
.emit('sayHello', null, 'mar~!');
  • 그냥 전화 후 현재 인스턴스의 이행을 보장하거나 (예) 추가
  • 따라서 클래스 이벤트의 인테리어, 현재 예를 들어이 점, 그리고이 단순히 추가하는 방법은 실현 될 수 반환
  • 재 작성 이벤트에주의를 기울 return
class Event {
    constructor() {
        this.events = {};
    }
    add(name, cb) {
        if (this.events[name]) {
            this.events[name].push(cb);
            return this; // 返回当前实例
        }
        this.events[name] = [cb];
        return this;
    }
    emit(name, ...args) {
        if (this.events[name]) {
            this.events[name].forEach(cb => {
                cb(...args);
            })
            return this;
        } else {
            console.error('[Event Error]: 该事件未注册')
        }
    }
}

그림 삽입 설명 여기

게시 된 177 개 원래 기사 · 원 찬양 22 ·은 20000 +를 볼

추천

출처blog.csdn.net/piano9425/article/details/103492525