You could turn it inside out with something like this:
function safeAdd(callback) {
return function(e) {
if(this.has(e))
return false;
this.add(e);
return callback.call(this, e);
};
}
and then you could do things like this:
var obj = {
onEvent: safeAdd(function(e) {
console.log('more logic', e);
}),
onPancakes: safeAdd(function(e) {
console.log('pancakes', e);
}),
has: function(e) { /* ... */ },
add: function(e) { /* ... */ }
};
Demo: http://jsfiddle.net/ambiguous/T6pBQ/
And if you need to support more arguments in your functions, switch call
to apply
and use arguments
instead of e
:
function safeAdd(callback) {
return function() {
if(this.has(arguments[0]))
return false;
this.add(arguments[0]);
return callback.apply(this, arguments);
};
}