EVENT EMITTERS LÀ GÌ ?
Trong nodejs
1 sự kiện (event) được mô tả như một chuỗi đơn giản với 1 callback tương ứng.
Một sự kiện
cần được phát hành nhiều lần hoặc có thể bạn chọn chỉ lắng nghe cho lần đầu
tiên phát hành đó.
Eventemitters
là một mô đun cho phép lập trình viên them một sự kiện lắng nghe và phát hành
những sự kiện.
Event
listener : đợi 1 sự kiện xảy ra như “khởi đầu”
Emitter: nó
thong báo toàn bộ sự kiện cho các bộ lắng nghe đó.
var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();
sử dụng:
emitter.on(‘name_of_event’,function(arg..){
//
rest of code
});
emitter.emit(‘name_of_event’);

Ví dụ:
var EventEmitter =
require('events').EventEmitter;
var emitter = new EventEmitter();
var fs = require('fs');
emitter.on('start_read',function(file_name){
console.log("Started Reading file....\n\n");
fs.readFile(file_name, 'utf8', function (err,data) {
if (err) {
emitter.emit('error','from_read');
}
else{
console.log("Done Reading file....\n\n");
emitter.emit('print_content',data);
}
});
});
emitter.on('print_content',function(data){
console.log("Printing content of file....\n\n");
console.log(data);
emitter.emit('done');
});
emitter.on('error',function(type){
console.log("Faced error while "+type);
emitter.emit('done');
});
emitter.on('done',function(){
console.log("Ok its done !");
});
emitter.emit('start_read','/etc/hosts');
Nhận xét
Đăng nhận xét