Skip to content

Commit

Permalink
[#1325] Add ability to remove listeners by function equality
Browse files Browse the repository at this point in the history
  • Loading branch information
cstigler authored and ScottDowne committed Sep 14, 2012
1 parent 0cd8d13 commit 27f6661
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 10 deletions.
16 changes: 14 additions & 2 deletions popcorn.js
Original file line number Diff line number Diff line change
Expand Up @@ -915,10 +915,22 @@
return this;
},
unlisten: function( type, fn ) {
var events = this.data.events[ type ];

if ( this.data.events[ type ] && this.data.events[ type ][ fn ] ) {
if ( !events ) {
return; // no listeners = nothing to do
}

if ( typeof fn === "string" && events[ fn ] ) {
delete events[ fn ];

delete this.data.events[ type ][ fn ];
return this;
} else if ( typeof fn === "function" ) {
for ( var i in events ) {
if ( hasOwn.call( events, i ) && events[ i ] === fn ) {
delete events[ i ];
}
}

return this;
}
Expand Down
41 changes: 33 additions & 8 deletions test/popcorn.unit.js
Original file line number Diff line number Diff line change
Expand Up @@ -1744,22 +1744,47 @@ asyncTest( "Custom", 1, function() {
p.emit( "eventz0rz" );
});

test( "on/off/emit", 4, function() {
test( "on/off/emit", 6, function() {

var $pop = Popcorn( "#video" );

$pop.on( "foo", function() {
deepEqual( this, $pop, "`this` is the popcorn instance" );
equal( typeof this.data.events.foo, "object", "events hash registered at this.data.events.foo" );
equal( Popcorn.sizeOf( this.data.events.foo ), 1, "Only one event is registered" );
var decoyCalled = false,
finishCount = 0;

$pop.off( "foo" );
var finishTest = function() {
finishCount++;

equal( this.data.events.foo, null, "events hash is null at this.data.events.foo" );
});
if( finishCount === 1 ) {
deepEqual( this, $pop, "`this` is the popcorn instance" );
equal( typeof this.data.events.foo, "object", "events hash registered at this.data.events.foo" );
equal( Popcorn.sizeOf( this.data.events.foo ), 2, "Two events are registered" );
} else if( finishCount === 2 ) {
equal( Popcorn.sizeOf( this.data.events.foo ), 1, "Only one event is registered" );
} else {
ok( false, "global off() is broken" );
}
};

var decoyFunc = function() {
equal( decoyCalled, false, "second callback on is called precisely once" );
decoyCalled = true;
};

$pop.on( "foo", finishTest );
$pop.on( "foo", decoyFunc );

$pop.emit( "foo" );

$pop.off( "foo", decoyFunc );

$pop.emit( "foo" );

$pop.off( "foo" );

equal( $pop.data.events.foo, null, "events hash is null at this.data.events.foo" );

$pop.emit( "foo" ); // shouldn't do anything

$pop.destroy();
});

Expand Down

0 comments on commit 27f6661

Please sign in to comment.