Tiny event emmiter in 128 bytes
var app = {event:{},Beam:function(a,b){var c,d=this,e=d.event[a]=d.event[a]||[];for(c in b&&b.call?+e.push(b):e)e[c].apply(d,arguments)}};
// Create a hello event
app.Beam('hello', function (event, name, lastname) {
console.log('Event fired "' + event + '": Hello ' + name + ' ' + lastname);
});
// Trigger the hello event without arguments
app.Beam('hello');
// Trigger the hello event with arguments
app.Beam('hello', 'Jack', 'Sparrow');
// Delete the hello event
delete app.event.hello;
// This will dont run because hello event does not exists
app.Beam('hello', 'Jack', 'Sparrow');
app.Beam('hello once', function(event, name, lastname){
console.log('Event fired "' + event + '": Hello ' + name + ' ' + lastname);
delete this.event[event];
});
// The first call of the hello once event
app.Beam('hello once', 'Jack', 'Sparrow');
// The second call of the hello once event will not fire because does not exists
app.Beam('hello once', 'Jack', 'Sparrow');
With a small trick, one can shave a few more bytes off that.
for(c in NaN){...}
does nothing and coercing a function like+e.push(function)
will result inNaN
, thus removing the need for if/else: