From 875c43cee48b1a865bb7e4e411648918c2a671c0 Mon Sep 17 00:00:00 2001 From: Mike Gerwitz Date: Thu, 31 Jul 2014 00:03:31 -0400 Subject: [PATCH] Added Evented#addListener as #on alias Consistent with Node.js' event API --- src/event/Evented.js | 13 ++++++++ test/event/EventedTest.js | 64 +++++++++++++++++++++------------------ 2 files changed, 48 insertions(+), 29 deletions(-) diff --git a/src/event/Evented.js b/src/event/Evented.js index 52e7f11..bc6e6dd 100644 --- a/src/event/Evented.js +++ b/src/event/Evented.js @@ -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 * from being invoked on future emits of event EV diff --git a/test/event/EventedTest.js b/test/event/EventedTest.js index 324e3bb..3f31792 100644 --- a/test/event/EventedTest.js +++ b/test/event/EventedTest.js @@ -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, ()=>{} ) ) - .to.throw( Error, badevent ); - } ); + expect( () => stub[ on ]( badevent, ()=>{} ) ) + .to.throw( Error, badevent ); + } ); - it( 'allows hooking declared events', () => - { - var name = 'testev'; - stub.evDefineEvents( [ name ] ) - .on( name, ()=>{} ); - } ); + it( 'allows hooking declared events', () => + { + var name = 'testev'; + stub.evDefineEvents( [ name ] ) + [ on ]( name, ()=>{} ); + } ); - it( 'returns self', () => - { - var name = 'testev'; + it( 'returns self', () => + { + var name = 'testev'; - var ret = stub.evDefineEvents( [ name ] ) - .on( name, ()=>{} ); + var ret = stub.evDefineEvents( [ name ] ) + [ on ]( name, ()=>{} ); - expect( ret ).to.equal( stub ); - } ); + expect( ret ).to.equal( stub ); + } ); - it( 'requires that listener is a function', () => - { - var ev = 'foo'; - stub.evDefineEvents( [ ev ] ); + it( 'requires that listener is a function', () => + { + var ev = 'foo'; + stub.evDefineEvents( [ ev ] ); - // OK - expect( () => stub.on( ev, ()=>{} ) ) - .to.not.throw( TypeError ); + // OK + expect( () => stub[ on ]( ev, ()=>{} ) ) + .to.not.throw( TypeError ); - // bad - expect( () => stub.on( ev, "kittens" ) ) - .to.throw( TypeError ); + // bad + expect( () => stub[ on ]( ev, "kittens" ) ) + .to.throw( TypeError ); + } ); } ); } );