Skip to content
Permalink
Browse files

Add the ability to remove a specific action or filter callback.

  • Loading branch information...
gcorne committed Jan 29, 2014
1 parent 45b52d1 commit c109d4f4cd19fc22d89779cfa1a9ef3edcea6ee0
Showing with 44 additions and 6 deletions.
  1. +19 −6 src/event-manager.js
  2. +25 −0 test/qunit-test.js
@@ -64,10 +64,11 @@
* Removes the specified action if it contains a namespace.identifier & exists.
*
* @param action The action to remove
* @param [callback] Callback function to remove
*/
function removeAction( action ) {
function removeAction( action, callback ) {
if( typeof action === 'string' ) {
_removeHook( 'actions', action );
_removeHook( 'actions', action, callback );
}

return MethodsAvailable;
@@ -109,10 +110,11 @@
* Removes the specified filter if it contains a namespace.identifier & exists.
*
* @param filter The action to remove
* @param [callback] Callback function to remove
*/
function removeFilter( filter ) {
function removeFilter( filter, callback ) {
if( typeof filter === 'string') {
_removeHook( 'filters', filter );
_removeHook( 'filters', filter, callback );
}

return MethodsAvailable;
@@ -125,9 +127,20 @@
* @param hook The hook (namespace.identifier) to remove
* @private
*/
function _removeHook( type, hook ) {
function _removeHook( type, hook, callback ) {
var actions, action, index;
if( STORAGE[ type ][ hook ] ) {
STORAGE[ type ][ hook ] = [];
if ( typeof callback === 'undefined' ) {
STORAGE[ type ][ hook ] = [];
} else {
actions = STORAGE[ type ][ hook ];
for ( index = 0; index < actions.length; index++ ) {
action = actions[ index ];
if ( action.callback === callback ) {
STORAGE[ type ][ hook ].splice( index, 1 );
}
}
}
}
}

@@ -160,9 +160,34 @@ test( 'fire action using method with context', function() {
};

wp.hooks.addAction( 'test.action', obj.method, 10, obj );
wp.hooks.doAction( 'test.action' );
wp.hooks.removeAction( 'test.action' );

} );

test( 'remove specific action callback', function() {
expect(1);
window.actionValue = '';
wp.hooks
.addAction( 'test.action', action_a )
.addAction( 'test.action', action_b, 2 )
.addAction( 'test.action', action_c, 8 );

wp.hooks.removeAction( 'test.action', action_b );
wp.hooks.doAction( 'test.action' );
equal( window.actionValue, 'ca' );
wp.hooks.removeAction( 'test.action' );

} );

test( 'remove specific filter callback', function() {
expect(1);
wp.hooks.addFilter( 'test.filter', filter_a )
.addFilter( 'test.filter', filter_b, 2 )
.addFilter( 'test.filter', filter_c, 8 );

wp.hooks.removeFilter( 'test.filter', filter_b );
equal( wp.hooks.applyFilters( 'test.filter', 'test' ), 'testca' );
wp.hooks.removeFilter( 'test.filter' );

} );

0 comments on commit c109d4f

Please sign in to comment.
You can’t perform that action at this time.