Last active
February 15, 2017 17:52
-
-
Save juanmaguitar/32b2f6d614744e10c166b1d6d238d648 to your computer and use it in GitHub Desktop.
Events Demo node.js | Constructor function inheriting from EventEmitter to "produce" objects w/ events
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = function(users) { | |
users.on("userAdded", function( msg ) { | |
console.log( new Date() ) | |
console.log( "DATA => " + msg ) | |
console.log( "LIST => " + users.listAll() ) | |
} ) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var UserList = require('./UserList') | |
var users = new UserList() | |
require('./log.js')(users) | |
setTimeout( function(){ | |
users.addUser("juanma") | |
}, 2000) | |
setTimeout( function(){ | |
users.addUser("alejandro") | |
}, 3000) | |
setTimeout( function(){ | |
users.addUser("david") | |
}, 5000) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var util = require("util"); | |
var EventEmitter = require("events").EventEmitter; | |
util.inherits(UserList, EventEmitter); | |
var users = []; | |
function UserList() {} | |
UserList.prototype.addUser = function(user) { | |
users.push(user) | |
this.emit("userAdded", user) | |
} | |
UserList.prototype.listAll = function() { | |
return users; | |
} | |
module.exports = UserList |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment