EventEmitter • manage "event handlers" • list of functions to be called per event • provide mechanism to trigger events
var util = require('util'), EE = require('events').EventEmitter; util.inherits(MyClass, EE); var myObj = new MyClass(); //nb using first class functions myObj.on('something', function);
exports.inherits = function (ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false } }); };
More than just core
CommonJS Modules
Library format for SSJS
math.js exports.add = function() { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) { sum += args[i++]; } return sum; }; increment.js var add = require('math').add; exports.increment = function(val) { return add(val, 1); }; var inc = require('increment').increment; var a = 1; inc(a); // 2
Protip exports.awesome = function() { //yay my code is awesomesauce }; var exports.fail = function() { //exports is a global //by redeclaring it as //a local variable //your code _will_ fail };
Exercise • Create a CommonJS module called "fish" • Provide functions to: • swim • mouth breath • flop around • Import your module into a node project • Call the various functions
Node Package Manager (NPM)
Recommend
More recommend