Added Evented#addListener as #on alias

Consistent with Node.js' event API
events
Mike Gerwitz 2014-07-31 00:03:31 -04:00
parent 74ccbff716
commit 875c43cee4
2 changed files with 48 additions and 29 deletions

View File

@ -235,6 +235,19 @@ module.exports = Trait( 'Evented',
}, },
/**
* Alias for #on
*
* @see {#on}
*/
addListener( ev, listener )
{
// we proxy to `on` (instead of the reverse) because `on` is
// traditionally more often used, so we want to save overhead there
return this.on( ev, listener );
},
/** /**
* Removes a previously hooked listener in constant time, preventing it * Removes a previously hooked listener in constant time, preventing it
* from being invoked on future emits of event EV * from being invoked on future emits of event EV

View File

@ -141,48 +141,54 @@ describe( 'event.Evented', () =>
} ); } );
describe( '#on', () => /**
* `addListener` is an alias for `on` (consistent with Node.js' API)
*/
[ 'on', 'addListener' ].forEach( on =>
{ {
it( 'does not allow hooking undeclared events', () => describe( ( '#' + on ), () =>
{ {
var badevent = 'bazbar'; it( 'does not allow hooking undeclared events', () =>
{
var badevent = 'bazbar';
expect( () => stub.on( badevent, ()=>{} ) ) expect( () => stub[ on ]( badevent, ()=>{} ) )
.to.throw( Error, badevent ); .to.throw( Error, badevent );
} ); } );
it( 'allows hooking declared events', () => it( 'allows hooking declared events', () =>
{ {
var name = 'testev'; var name = 'testev';
stub.evDefineEvents( [ name ] ) stub.evDefineEvents( [ name ] )
.on( name, ()=>{} ); [ on ]( name, ()=>{} );
} ); } );
it( 'returns self', () => it( 'returns self', () =>
{ {
var name = 'testev'; var name = 'testev';
var ret = stub.evDefineEvents( [ name ] ) var ret = stub.evDefineEvents( [ name ] )
.on( name, ()=>{} ); [ on ]( name, ()=>{} );
expect( ret ).to.equal( stub ); expect( ret ).to.equal( stub );
} ); } );
it( 'requires that listener is a function', () => it( 'requires that listener is a function', () =>
{ {
var ev = 'foo'; var ev = 'foo';
stub.evDefineEvents( [ ev ] ); stub.evDefineEvents( [ ev ] );
// OK // OK
expect( () => stub.on( ev, ()=>{} ) ) expect( () => stub[ on ]( ev, ()=>{} ) )
.to.not.throw( TypeError ); .to.not.throw( TypeError );
// bad // bad
expect( () => stub.on( ev, "kittens" ) ) expect( () => stub[ on ]( ev, "kittens" ) )
.to.throw( TypeError ); .to.throw( TypeError );
} );
} ); } );
} ); } );