I have code in the following form in which the user may specify a callback which will be called at a later time:
var _deferred = [];
var deferred = function(callback) {
_deferred.push(callback);
}
var doDeferred = function() {
for(var i = 0, max = _deferred.length; i < max; i++) {
_deferred[i].call();
}
}
for(var i = 0; i < 5; i++) {
deferred(function() {
console.log("Some deferred stuff");
});
}
doDeferred();
I would like to recognize that the callback specified to deferred() is an anonymous function resolving to the same origin, and only allow it to be added once. Aka in the bottom for loop it would throw an exception when i = 1.
Like:
var deferred = function(callback) {
if(_deferred.indexOf(callback) !== -1) {
throw "Already added!";
}
_deferred.push(callback);
}
I can think of many ways of doing this by adding a "key", but I'm wondering if I can use something along the lines of Function.caller to create a "source hash"?
Is there a solution for this out there already that I'm not seeing? I'd really prefer to accept this burden onto myself rather than push it out to the caller of deferred and have them provide some sort of unique id.
EDIT:
To clarify any confusion.
Yes each call to deferred is with a unique function object, has its own closure, etc. Therefore my indexOf will always fail. That is not a point of confusion.
The question is that these anonymous functions are declared in the same place, they are the same code, how can I determine that? I'm looking to determine declarative equality, not instance equality. I was thinking I could somehow create a hash based on caller of deferred...
CONCLUSION:
Thanks guys, it seems like there is no really elegant solution here. The toString method is not definitive (different functions with same body will test equally as strings) - and is just ugly. I'm going to put the burden on the caller.