Is it possible to trigger the eventListener just once for every instance of my constructor?

I have a common property that is shared among all instances of my constructor:

function Me() { }
Me.prototype.window = {};

I want to update this property when the window is resized, but I only want it to happen once for each resize event, regardless of how many instances of my constructor exist.

If I define the eventListener in the initialization of my instances like below, it will trigger multiple times

function Me() {
  window.addEventListener('resize', function() {
    this.window = window.outerWidth;
  }.bind(this));
}
var a = new Me();
var b = new Me();
// The callback is triggered twice on resize

Is there a way to accomplish this?

Answer №1

Is there a way to accomplish this task?

One approach is to have a variable that determines whether the event handler should be bound or not. Then, you can simply check this variable in the constructor:

if (shouldBindHandler) {
  // ... binding the handler
  shouldBindHandler = false;
}

The decision of how and where to store this variable is left to your discretion.

Answer №2

Sharing the progress of providing answers and solutions to OP, who had not shared all necessary information upfront. Despite offering a solution that was later marked correct by someone else, it was initially dismissed.


Initially suggested a straightforward solution:

Moved code outside constructor function to update shared property for all instances on window resize.

window.addEventListener('resize', function() {
  Me.prototype.window = window.outerWidth;
};

Later, OP noted that registering callback on prototype could cause issues if no instances of Me existed.


Suggested tracking instance existence before registering event listener, which OP eventually adopted.

Introduced global variable to track instance presence:

// Global variabel to track if Me instances exist
var meInstances = false

var me1 = new Me();
meInstances = true;

if(meInstances){
   window.addEventListener('resize', function() {
     Me.prototype.window = window.outerWidth;
   };
}

Received feedback critiquing this approach as adding unnecessary complexity and lack of robustness. OP then devised an array-based solution to address these concerns.


Proposed another alternative utilizing callbacks within constructor function, albeit not fully endorsing it due to evolving constraints set by OP.

function Me() {
  // This code only runs when instance is being made

  // Instance registers a callback
  window.addEventListener('resize', function() {

    // Callback modifies single Prototype that all instances share
    Me.prototype.window = window.outerWidth;
  });
}

Me.prototype.window = {};

Despite various suggestions and adaptations, none were ultimately accepted as a suitable solution.

Answer №3

Here is the solution incorporated into the final code:
I included a destroy method for thoroughness:

function Me() {
  this.init();
}

Me.prototype.window = 0;

// function to update this.window
Me.prototype.onResizeBound = null;
Me.prototype.onResize = function() {
  Me.prototype.window = window.outerWidth;
};

// initialize event listener if there are no instances of Me
// then add this instance to the list of instances
Me.prototype.init = function() {
  if (this.instances === 0) {
    Me.prototype.onResizeBound = this.onResize.bind(this);
    window.addEventListener('resize', Me.prototype.onResizeBound);
  }
  this.instances++;
};

// remove this instance from the list of instances
// if no more instances exist, remove the event listener
Me.prototype.destroy = function() {
  this.instances--;

  if (this.instances === 0) {
    window.removeEventListener('resize', Me.prototype.onResizeBound);
  }
};
Me.prototype.instances = 0;

Example:

var a = new Me(); // event listener added
var b = new Me(); // event listener not added as one already exists
b.destroy(); // event listener not removed since one instance still remains
a.destroy(); // event listener removed as no other instances exist

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

Steps to creating a custom text editor using React for generating blog content and storing it in a MongoDB database

I have a challenge of building a rich text editor for my web app, specifically for creating blog posts that will be saved in the database for user viewing. Initially, I planned to use a form with input fields where the title and content of the blog post w ...

What is the best way to handle multiple axios calls with pagination in a React application?

Discussing React Pagination and Handling Multiple Axios Calls In my current project, I am faced with the challenge of mapping through an array of numbers and making sequential API calls for each one. The API I'm working with returns paginated results ...

JQuery method for extracting a specific span's content from a div

I am faced with extracting specific text from a span within a div element. Below is the code snippet for my Div: '<div class="dvDynamic_' + pid + '"><p hidden="true">'+pid+'</p><span class="count_' + pid ...

What is the best way to define file paths in a webpage to ensure that the same file works seamlessly on both server and

Currently, I am working on developing a website locally with the intention of later transferring it via FTP to my server. In my index.php file, there is a line that reads: <?php include($_SERVER['DOCUMENT_ROOT'] . "/includes/header.php");?&g ...

What is the process for sending Raw Commands to a Receipt Printer using Node.JS?

My Current Project I am currently working on integrating a receipt printer that supports ESC/P raw printing into an app for remote printing of receipts. The Approach I Am Taking To achieve this, I am utilizing the PrintNodes API to send data from my app ...

Using Flickity API in Vue 3 with Typescript Integration

I have encountered an issue with implementing Flickity in my Vue 3 application. Everything works perfectly fine when using a static HTML carousel with fixed cells. However, I am facing difficulties when attempting to dynamically add cells during runtime us ...

Ways to remove code from production during build process?

Is there a way to omit typescript code from getting bundled by webpack during build process? Let's say I have the following line of code in my app.ts file (a nodejs application): const thisShouldNotBeInProductionBundleJustInDevBundle = 'aaaaaaa ...

JavaScript code that iterates through all files in a designated folder and its subfolders using a for loop

I am looking to combine two JavaScript scripts into one, but I'm not sure how to do it. The first script uploads files from a specified folder to VirusTotal for scanning and returns the scan result. The second script lists all files in the specified ...

The JSON data parser does not support the use of single quotation marks

Using PHP, I am storing user "comments" from my website in a database and escaping special characters with mysql_real_escape_string(). This helps to avoid any issues with single quotes (') or double quotes ("). To display these comments on the website ...

Issue encountered during rendering: The function used is not a filter

Everything works fine with the search filter and pagination on the initial load. However, upon clicking to go to the next page, an error occurs stating **'Error in render: "TypeError: this.tickets.filter is not a function"'**. This issue can b ...

Introduction to AJAX: Conditional Statements

Within the menu.html file, there are various menu items (a href links) called menu_1, menu_2, and so on. The map.js file is responsible for displaying map content by utilizing an API to showcase different layers and maps. Even though there are many maps t ...

Is there a way for me to determine which .js script is modifying a particular HTML element?

Let's take a look at a specific website as an example: This particular website calculates value using a .js script embedded in the HTML itself. Upon inspecting the source code by pressing F12, we can locate the element containing the calculated valu ...

Prevent links from being clicked multiple times in Rails using Coffeescript

Please make the following link inactive after it has been clicked once <%= link_to "Submit Order", {:action => "charge"}, class: 'btn btn-primary', id: 'confirmButton' %> To permanently deactivate the link, use the code below ...

Display a pdf stream within a fresh window

I have a PDF document generated on the server that I need to display on the client side. The code on the server looks like this: ByteArrayOutputStream baos = generatePDF(); response.setContentType("application/pdf"); response.setHeader("Content-Dispositio ...

Simulating NextJS router triggers using Jest

I've been attempting to simulate NextJS router events using Jest. I came across a useful resource at NextJS router & Jest. The approach outlined there closely resembles mine. Unfortunately, the solution provided in that post is not yielding the d ...

What is the proper way to credit the glyphicons element in Twitter's bootstrap framework?

According to the section on icons in the Base CSS page of GitHub's Twitter bootstrap, Glyphicons Halflings were not originally available for free. However, thanks to an agreement between Bootstrap and the creators of Glyphicons, developers can now use ...

Prevent the left border from displaying on a link that wraps to a new line

Excuse me, I am facing an issue with a pipe separator in my subnav bar between links. The problem is that the first link on a new line retains the left-border that should be disabled. How can I prevent this border from appearing on the first link of a new ...

The method JSON.stringify is not properly converting the entire object to a string

JSON.stringify(this.workout) is not properly stringifying the entire object. The workout variable is an instance of the Workout class, defined as follows: export class Workout { id: string; name: string; exercises: Exercise[]; routine: Ro ...

The formControl value is not being shown on the display

I am facing an issue with a form that has multiple fields created using formGroup and formControlName. The challenge arises when I launch the application and need to retrieve data from the back end to display it on the view. The specific problem I'm ...

Troubleshooting issues with rowspan in a Datatable

I am currently utilizing jQuery DataTables to display my grid data and implementing the rowspan concept with the rowsGroup option. Initially, it works well by spanning some rows and looking visually pleasing, but eventually, it starts failing. Here are so ...