Kriem
Kriem

Reputation: 8705

jQuery.Callbacks - Removing anonymous function callbacks

After adding a callback function to $.Callbacks(), I want to remove it again:

var callbacks = $.Callbacks(),
    foo = function() { console.log('Hello world') };

callbacks.add(foo);
callbacks.fire(); // logs 'Hello world'
callbacks.remove(foo);
callbacks.fire(); // nothing to trigger, removed perfectly

So, that works, but now I want to add an anonymous function, like so:

callbacks.add(function(){ console.log('Hello anonymous world') });
callbacks.fire(); // logs 'Hello anonymous world'

Looks fine, but I can't remove the function anymore:

callbacks.remove(function(){ console.log('Hello anonymous world') });
callbacks.remove();

callbacks.fire(); // still logs 'Hello anonymous world'

Is there a way to overcome this?

Upvotes: 1

Views: 2387

Answers (2)

papiro
papiro

Reputation: 2365

You could remove it from within the function itself (like at the last line of the function) using arguments.callee (a reference to itself) although arguments.callee is not valid in 'strict mode'.

Upvotes: 0

Jonathan M
Jonathan M

Reputation: 17461

Per OP Request:

Functions are identified by pointer. You have no pointer to your anonymous function, so you have nothing to pass to remove() to tell it which function to remove. Simply passing a duplicate function doesn't do it, because the duplicate has a different pointer. You need to stick with assigning the function to a variable, then passing that variable to remove().

Reference: http://api.jquery.com/category/callbacks-object/

Upvotes: 3

Related Questions