-2
實現自定義事件對象的API,並在註釋(Test 1)中顯示函數。 需要通過擴展(測試2)重用Event對象的api。如何實現自定義事件對象的api?
Event.on('test',function(result){
console.log(result);
})
Event.on('test',function(){
console.log('test');
})
Event.emit('test','hello world');//output 'test'和'hello world'
//test2
var person1 = {};
var person2 = {};
Object.assign(person1,Event);
Object.assign(person2,Event);
person1.on('call1',function(){
console.log('person1');
});
person2.on('call2',function(){
console.log('person2');
});
person1.emit('call1'); //output 'person1'
person1.emit('call1'); //not output
person1.emit('call1'); //not output
person1.emit('call1'); //output 'person2'
var Event= {
//through on api watch event evenName
//if event eventName was triggered,execute callback function
on:function(eventName,callback){
//your code
},
//trigger event eventName
emit:function(eventName){
//your code
}
}
等都不是代碼寫作服務。這看起來很像「請填空」。你能告訴我們你已經嘗試了什麼,以及你的問題在哪裏? – Bergi
假設這在節點上,爲什麼不使用內建的[EventEmitter](https://nodejs.org/api/events.html)? – Bergi