Saturday 31 August 2013

Javascript return enclosing function

Javascript return enclosing function

I have a simple scenario in which I check if something exists before
adding it, if it does, I return the function (hence exiting). I use this
pattern many times and I would like to decouple it in another simple
function.
function onEvent(e){
if( this.has(e) )
return
this.add(e);
// More logic different on an event-basis
}
I would like to decouple it like so:
function safeAdd(e){
if( this.has(e) )
return
this.add(e);
}
function onEvent(e){
safeAdd(e);
// More logic
}
But obviously doing so just returns safeAdd and doesn't exit from onEvent,
and the rest of the logic gets executed anyways.
I know I could do something like:
function safeAdd(e){
if( this.has(e) )
return false
this.add(e);
return true
}
function onEvent(e){
if( !safeAdd(e) )
return
// More logic
}
But, since I repeat this a lot, I would like to be as concise as possible.

No comments:

Post a Comment