The correct way to properly define an eventEmitter in JavaScript

I am looking to create a helper object with a function that will trigger on each "orientationchange" event of the window.

Below is my code, but it is not working correctly. Can you help me define the onRotate function properly so that I can use it globally?

    <script type="text/javascript">
    'use strict';
    var GlobalHelper = (function () {

        var me = {
            onRotate: onRotate // struggling with this part
        }

        function onRotate() {
            window.addEventListener("orientationchange", function (event) {
                console.log(event.target.screen.orientation.angle);
            });
        }

        return me;

    })();

    GlobalHelper.onRotate = function (e) {
        console.log(e);
    }

</script>

Answer №1

I figured out the solution to my question on my own, and surprisingly, it was quite simple.

   <script type="text/javascript">
    'use strict';
    var GlobalHelper = (function () {

        var me = {
            onRotate: function (e) {  }
        }

        function _init() {
            window.addEventListener("orientationchange", function (event) {
                me.onRotate(event);
            });
        }

        _init();

        return me;

    })();

    GlobalHelper.onRotate = function (e) {
       console.log(e);
    }

</script>

Answer №2

If you want to enhance your code with a custom programmable method for creating listeners and bonded functions, here's an option for you to explore. You can experiment with it by running the code snippet and interacting with the results window by pressing keyboard keys.

// Define the bindFn function
const bindFn = e => {
  // Object to store functions
  let fns = {};
  
  // Event listener to execute all functions in fns object
  window.addEventListener(e, event => {
    for(const f in fns) fns[f](event);
  });
  
  // Return method for adding new functions
  return {
    add: (name, fn) => {
      if(!fns[name]) fns[name] = fn;
      else console.log(`Function named ${name} already exists, skipping...`);
    }
  };
};

// Create binder for orientation change event
const OrCh = bindFn("orientationchange");

// Add a function to run on this event
OrCh.add('log', event => console.log(event.target.screen.orientation.angle));

// Test with another easy-to-trigger event
const KeyP = bindFn("keypress");

// Add logger
KeyP.add('log', event => console.log(`key pressed: ${event.code}`));

// Add an alternative function
KeyP.add('logAlt', event => console.log(`Alternative function triggered: ${event.code}`));

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

How can I utilize a CDN for JavaScript libraries in Gulp?

As a newcomer to AngularJS and Gulp, I recently encountered an example where certain libraries are copied by Gulp from the 'node_modules' folder into a 'js/lib/angular2' directory: gulp.task('libs', function() { return gulp. ...

Customizing Angular 2's Webpack environment setup dynamically

Currently, I have set up Webpack to compile my Angular project. Within my project, there is an important file called env.js: module.exports.ENV = { API_URL: "http://localhost:5001/", ... }; In the webpack.common.js file, I am referencing this file l ...

I am a beginner in JavaScript and I'm struggling to understand why it is not executing the else statement

As a newcomer to JavaScript, I have only learned from one website. Unsure if my code is outdated or contains elements of other software like jQuery, all I know is that it refuses to execute the else statement. <!Doctype html> <html> <body ...

Different Ways to Access an Array in an EJS Template

After receiving a list of IDs from an API, I need to include them in a URL within an EJS template to retrieve the correct items. For example, the URL format is: Here are some example IDs: 526 876 929 The desired output inside the EJS template: <li&g ...

Sort an array by mapping it in decreasing order based on the total sum of its elements

I came across a JSON structure that looks like the following: { "user": [ {"username": "x1", "pfp": "", "scores": [{"easy": 10, "normal": 1, "hard": 2, "oni&q ...

How to send a function from a parent component to a child component in Vue.js

I'm trying to figure out how to pass the parent component's method to the child component. Here's the scenario: when I click the confirm button on my modal (child component), it needs to send the data from the parent form (parent component). ...

anychart: The right side of Gantt Charts is being cut off or trimmed

I am utilizing anychart for my user interface. My data timelines are in epoch milliseconds. When trying to create a Gantt chart, I notice that the right side is being trimmed. Can someone please assist me with this issue? https://i.sstatic.net/H6LHk.png ...

Retrieving time zone using offset with javascript

I am looking for a way to schedule time-based events on my server operating in UTC time. For the user interface, I need to input 2 parameters: The local time when the scheduled event should trigger The timezone offset Instead of displaying timezone n ...

The functionality of Bootstrap tabs is compromised when used within a modal dialog

I am encountering an issue while using Django and Bootstrap to implement nav-tabs within a modal that is displayed upon clicking a button. The problem lies in the fact that when a tab is clicked, its content does not appear. Below is a basic example: {% ...

Combining Extjs combo with autocomplete functionality for a search box, enhancing synchronization capabilities

When using autocomplete search, I've encountered an issue. If I type something and then make a mistake by deleting the last character, two requests are sent out. Sometimes, the results of the second request come back first, populating the store with t ...

Is there a way to dynamically incorporate line numbers into Google Code Prettify?

Having some trouble with formatting code and inserting/removing line numbers dynamically. The line numbers appear on the first page load, but disappear after clicking run. They don't show at all on my website. I want to allow users to click a button a ...

Incorrect footer navigation on my Vuepress website

I'm in the process of developing a vuepress single page application for showcasing and providing downloads of my personal game projects. When it comes to website navigation, I am aiming to utilize the native sidebar exclusively. This sidebar will hav ...

"Step-by-Step Guide: Activating Tab Functionality in J

I'm facing an issue here - I've been attempting to log the event's key code and I keep getting key number (9). I believe my script isn't disabling event.keyCode properly, hence the key function remains active. What changes should I make ...

Setting a value in the selectpicker of rsuitejs involves assigning a specific value to the

const _DATA = [{ code: 'code1', name: 'Jagger' },{ code: 'code2', name: 'Tigger' },{ code: 'code3', name: 'Lion' }] <SelectPicker data={_DATA.map(x => {return {label: x.n ...

Custom attribute in ReactJS component - I am not defined in my custom attribute in React component

I am currently working with ReactJS and I am facing an issue regarding accessing a custom attribute -name- of my ReactJS component. Despite trying to use e.target.name, it keeps returning "undefined" on my console. I cannot seem to figure out why this is ...

When attempting to set a dynamic src tag for embedding a Google Map in a React application, an X-Frame-Options

I'm attempting to display a specific location using an iframe embed from Google Maps (shown below): <iframe width="100%" height="200" frameBorder="0" scrolling="no" marginHeight={0} marginWidth={0} id="g ...

Ways to update the select field without having to reload the entire page

I am working on a unique feature that involves two levels of drop down menus. When a user makes a selection in the first level, a corresponding set of options will appear in the second level. For example, I have 6 options in the first level, each with its ...

Mapping a bar chart on a global scale

Are there any methods available to create bar charts on a world map? The world map could be depicted in a 3D view resembling a Globe or in a 2D format. It should also have the capability to zoom in at street level. Does anyone have suggestions or examples ...

Choose all the alternative A radio buttons utilizing JavaScript

If the "4 stars" option is selected at the top, I want all corresponding "4 stars" options in the form to be automatically selected. Similarly, if "3 stars" is chosen, I need all the "3 stars" options to be selected. I attempted to achieve this functionali ...

Use PHP to highlight the row that has been selected in an HTML table

I am currently working on a project where I have styled multiple HTML tables on my website using alternating gray and white bands. Now, my goal is to highlight the selected row in a darker shade of gray. I have experimented with various solutions, and the ...