Skip to content

Instantly share code, notes, and snippets.

@nobitagit
Last active March 12, 2017 22:44
Show Gist options
  • Save nobitagit/a9e6f72119f30f9db2cd91297ae26dba to your computer and use it in GitHub Desktop.
Save nobitagit/a9e6f72119f30f9db2cd91297ae26dba to your computer and use it in GitHub Desktop.
Node basic examples
// DOCS https://nodejs.org/api/events.html
const Emitter = require('events');
class Basket extends Emitter {
constructor(total) {
super();
this.total = total || 0;
this.currency = '£';
}
init() {
this.initialised = true;
this.items = [];
this.emit('onInit', this.currency);
}
add({amount, price, productId}) {
this.items = [...this.items,
{
amount,
price,
productId,
}];
this.emit('added', productId);
}
}
const basket = new Basket(200);
basket.once('onInit', function(currency) {
console.log(`New Basket created with value ${this.total}${currency}`);
});
basket.init(); // fires listener
basket.init(); // no log
basket.init(); // no log
basket.init(); // no log
basket.init(); // no log
basket.on('added', function(pid) {
console.log(`Added ${pid}`);
});
// logs every time
basket.add({productId: 0});
basket.add({productId: 10});
basket.add({productId: 20});
basket.add({productId: 30});
// Always remove the listeners when they are not needed anymore
basket.removeAllListeners('added');
basket.removeAllListeners('onInit');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment