Incorporating a function within another function to mitigate redundancy in code: A guide

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.

Answer №1

Implement a function decorator that generates and returns another function. Utilize closure to handle the execution logic.

function eventHandlerWrapper(original_function) {
 return function(){
   if (typeof _cookie !== 'undefined') { 
      console.log('Executing the event because the cookie is present');
      return original_function.apply(this,arguments);
     }
 }
}


var emailBlurEvent = eventHandlerWrapper(function(){
   ...... // code within the function
});
$('#email').blur(emailBlurEvent);


var formSubmitWrapped = eventHandlerWrapper(formSubmitFunction); 
formSubmitWrapped();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determine the aspect ratio of the image and incorporate it into the query string

In my current code, I am extracting the dimensions of an image obtained from a cropper tool. I then calculate the aspect ratio of the image by dividing the height by the width. This value is then incorporated into the query string url: urlLocation + imag ...

What do I do when I get a "findByIdAndUpdate is not a function" error from my controller after requiring the model

I am currently developing a web application for my company that allows us to access and manage a database of customers and their information using MongoDB, Mongoose, and Express. Our company specializes in reselling used copiers/printers and offering maint ...

Chrome is opting to download PDF files rather than display them in the

For the past 3-4 years, I have had this code successfully running in production using Vue.js. <object :data="pdfUrl" type="application/pdf" width="100%" height="100%" style="min-height: 700px"> </object> When clicking a button, ...

Issue with sticky navbar in parallax design

I have been working on a website where all pages feature a header and a navbar located just below it. As the user scrolls down the page, I want the navbar to stick to the top of the screen once it reaches that position. However, on one specific page, I am ...

``Enhanced feature allowing users to input different zip codes in a weather

Currently, I am exploring the integration of a weather plugin found at: http://jsfiddle.net/fleeting/a4hbL/light/ The plugin requires either a zipcode or woeid to function. Instead of hardcoding the zipcode, I am looking to make it dynamic so that users f ...

What is the correct way to inspect the HTTP request body and reject it if it does not adhere to the specified pattern when working with a basic NodeJS server?

I am currently facing a challenge while developing a server using solely nodeJS libraries and methods. I am struggling to validate the request body format and promptly respond with a client error status code type (400-499). Below is the JavaScript code sn ...

What occurs when the state of a DOM element is altered?

I've come across a few articles discussing the Real DOM and Virtual DOM, but I'm still finding it difficult to grasp the concept fully. When updating an element on a webpage, does the browser render the entire page or just the specific part bein ...

Attempting to resolve the Bootstrap issue, currently in search of a suitable solution

Today I made the decision to utilize bootstrap to create a menu, but unfortunately, I've encountered a strange bug or conflict involving jQuery, potentially the UI, and Bootstrap. If you'd like, you can take a look at the picture provided in the ...

I'm having trouble retrieving the precise coordinates of a mouse click. Can anyone help troubleshoot my code?

When attempting to display something at the exact place where a mouse click occurs, I utilized the following code snippet: $('#my-graph').mousedown(function(evt){ // show object at: var x= evt.screenX, y=evt.screenY; //or sho ...

What is the process for creating a duplicate element within the target div after the original element has been dropped?

Imagine a scenario where the "HI" div is dragged into the "DRAG HERE" div, causing the "HI" div to be removed from its original location. What if, instead of disappearing, dragging the "HI" div to another location generated a new "HI" div? /** * Fu ...

Combating React SetState Race Conditions with the Power of Promise.all

componentDidMount() { Promise.all([OfferCreationActions.resetOffer()]).then( () => { OfferCreationActions.updateOfferCreation('viewOnly', true); OfferCreationActions.updateOfferCreation('loadingOffer', true); ...

Font size determined by both the width and height of the viewport

I'll be brief and direct, so hear me out: When using VW, the font-size changes based on the viewport width. With VH, the font-size adjusts according to the viewport height. Now, I have a question: Is there a way to scale my font-size based on ...

Verifying if a specific class input exists within a table using JavaScript

Issue Description: I currently have a table with x number of rows and y number of columns. The structure of most rows contains similar inputs in terms of class and type, but not all of them. I perform calculations on the entire table using JavaScript bas ...

Expression validation in AngularJS is a powerful tool for ensuring that

Attempting to implement input validation using an Angular expression because validation data will be sourced from the database. Attempting the following code: controller vm.key="ng-required" vm.value="true" html <input type="text" name="fi ...

The focal point of a Three JS rotation

My goal is to rotate the geometry around a pivot point and set that as the new definition of the geometry. I want the current rotationZ to become the new rotationZ 0 without having to keep editing the rotationZ. This way, when I create a new rotation task ...

Different ways to use functions with AngularJS, including the parsley and reset options

Here are two functions I use to reset error messages and form field values: $("#modal_form").parsley().reset();//This only resets error messages, not form field values $("#modal_form")[0].reset();//This only resets form field values, not error messages I ...

Set the text field to be editable or readonly based on certain conditions

Is there a way to conditionally enable or disable an editable field (edit/read only)? I have tried using session role from the database to set conditions on the text field, but I am unsure of how to proceed... <?php include('session.php'); ?& ...

What is the reason for the automatic loading of coffee files in app/assets/javascripts across all files?

I have a question about organizing my Javascript files in my app. I have multiple files in the app/assets/javascripts folder, and for testing, I have written some code in a file named test.coffee: $ -> $(document).ready -> alert("Hey"); When ...

Trouble with ES6 Arrow Functions, Syntax Error

I am encountering an issue with my JS class structure: class Tree { constructor(rootNode) { this._rootNode = rootNode; rootNode.makeRoot(); } getRoot() { return this._rootNode; } findNodeWithID(id) ...

Unusual situation observed in ExpressJS: Callback function fails to execute

Currently, I am facing an issue with my web app built using expressjs and node. It seems that the functionality is not working correctly. An unusual situation has occurred where accessing the first link in the browser yields the expected results, while th ...