fildred13
fildred13

Reputation: 2350

How to wrap a function in a function to avoid code repetition

Using jQuery in this example, though that should have no bearing on the answer.

I have two events that fire on page load:

triggerEvent(SNVisitsForm); 
$('#email').blur(triggerEvent(SNEnterEmail));

The first simply fires when the user visits the page, and the other is a listener which will fire when the user blurs the email field.

triggerEvent is a function which I am using to "wrap" many disparate functions with one simple conditional. The goal is to have this conditional be able wrap any arbitrary function:

function triggerEvent(wrapped_function) {
if (typeof _cookie !== 'undefined') {
        wrapped_function();
        console.log('Doing the event, because the cookie is defined');
    }
}

That function works just fine for the first of the two examples (that is, (triggerEvent(SNVisitsForm); functions perfectly).

However, since SNEnterEmail starts like this:

function SNEnterEmail(event) {
    var email = event.target.value;

I need to pass the event through the wrapper function to the wrapped function. As you can see, sometimes an event doesn't exist (as in the case of the first of the two examples).

Is there a more "javascript" way to do this? Surely the answer isn't "just put that conditional code around every single one of your calls that need it" or "put it into every single function that needs it." What is the javascript-approved way to accomplish this avoidance of repetition?

Edit: I should add that the answer may well be something completely different from wrapping a function in a function. It was just the best way I could think to illustrate what I was trying to do.

How the accepted answer solved this for me:

I did use adrian's wrapper function, and then a quick modification to my calls made everything work:

if (window.location.pathname == '/') {
    (triggerEvent(SNVisitsForm)()); 
}
$('#email').blur(triggerEvent(SNEnterEmail));

I'm not sure why adrian changed the wrapped functions to vars, I left them as functions. Then I simply make "standard" calls of the wrapper function (i.e., those that are not bound to listeners) Immediately Invoked Function Expressions.

Upvotes: 2

Views: 91

Answers (1)

adrianj98
adrianj98

Reputation: 573

Just create a function decorator that returns a function. closure will take care the rest.

function triggerEventWrapper(wrapped_function) {
 return function(){
   if (typeof _cookie !== 'undefined') { 
      console.log('Doing the event, because the cookie is defined');
      return wrapped_function.apply(this,arguments);
     }
 }
}


var SNEnterEmail = triggerEventWrapper(function(){
   ...... the function decloration
});
$('#email').blur(SNEnterEmail);


var  SNVisitsFormWrapped = triggerEventWrapper(SNVisitsForm); 
SNVisitsFormWrapped();

Upvotes: 2

Related Questions