Using jQuery in this instance, although that should not impact the response.
Upon loading the page, two events are triggered:
triggerEvent(SNVisitsForm);
$('#email').blur(triggerEvent(SNEnterEmail));
The first event triggers when a user visits the page, while the second is a listener activated when the email field is blurred.
The function triggerEvent
is used to encapsulate various functions with a single condition. The aim is to encompass any arbitrary function within this condition:
function triggerEvent(wrapped_function) {
if (typeof _cookie !== 'undefined') {
wrapped_function();
console.log('Executing the event, as the cookie is defined');
}
}
This function works effectively for the initial example (triggerEvent(SNVisitsForm);
works perfectly).
However, since SNEnterEmail
initiates like this:
function SNEnterEmail(event) {
var email = event.target.value;
I need to pass the event through the wrapper function to the enclosed function. Occasionally, there may be instances where an event is not present (as seen in the first scenario of the two examples).
Is there a more "javascript" approach to tackle this? Surely the solution isn't just to place that conditional code around each call that requires it or insert it into every function that needs it. What is the recommended way in JavaScript to avoid repetitive tasks?
Edit: It's worth mentioning that the resolution may involve a different method than wrapping a function inside another function. This was just the clearest way I could convey what I intended to achieve.
The effective way the accepted answer addressed this issue:
I incorporated Adrian's wrapper function, and a minor adjustment to my calls resolved everything:
if (window.location.pathname == '/') {
(triggerEvent(SNVisitsForm)());
}
$('#email').blur(triggerEvent(SNEnterEmail));
It is unclear why Adrian converted the wrapped functions to variables; I retained them as functions. Subsequently, I merely utilized "standard" calls of the wrapper function (i.e., those not tied to listeners) as Immediately Invoked Function Expressions.