2020年3月1日 星期日

Node.JS - 簡化函式宣告

目前在學習Node.JS
有一些地方看不太懂,
多看一些網站,總算是了解了,
原來是省略了一些部分,
不過,這樣的寫法可讀性應該會變差,
但是,還是必需要了解別人是在寫什麼。


原本的程式碼

// get the reference of EventEmitter class of events module
var events = require('events');
// create an object of EventEmitter class by using above reference.
var em = new events.EventEmitter();

// bind the function with a event
em.on('FirstEvent', function (data) {
 console.log('First subscriber:' + data);
});
// emit event
em.emit('FirstEvent', 'I have entered the first Event!!');

實際上可以寫的清楚一點如下,
可讀性比較高


// get the reference of EventEmitter class of events module
var events = require('events');
//create an object of EventEmitter class by using above reference.
var em = new events.EventEmitter();

// Create an event handler:
var myEventHandler = function (data) {
 console.log('First subscriber:' + data);
}
// bind the function with a event
em.on('FirstEvent', myEventHandler);

//bind the function with a event
//em.on('FirstEvent', function (data) {
// console.log('First subscriber:' + data);
//});
//emit event
em.emit('FirstEvent', 'I have entered the first Event!!');

這個寫法必需懂,
因為看起來很多Node.JS都會用這個寫法!!

參考資料:
Node.js Events
Day11 - Node.js EventEmitter

1 則留言:

ianthaeagar 提到...

Casinos near mylton, OH, USA - MapYRO
Casinos near me. Casinos in near me. Casino: 36. Location: Unknown. 의정부 출장샵 Nearby 밀양 출장안마 Casinos: 641 Highway 춘천 출장안마 50, Columbus, Ohio 문경 출장안마 18406. 메이피로출장마사지