Invoking a JavaScript prototype method within a different method

I have been struggling for some time now as I am not very proficient in javascript object-oriented programming. My goal is to create a callback API to detect when an element is being scrolled. However, I am facing difficulty in invoking the prototype method from another method. Can someone please assist me with this?

     //HTML
     //<div style="width:500px;height:500px;"id="myElement"></div>

     //JS
       mousewheelListen=function(){
            this.el.addEventListener('wheel',);//How can I call Scroller.prototype.scrolling() ?
        }
        Scroller=function(el){//Constructor
            this.el=el;
            mousewheelListen.call(this);
        }
        Scroller.prototype.scrolling=function(callback){//
            callback.call(this);
        }
        
        
        var el=document.getElementById('myElement');
        var myScroller=new Scroller(el);
        myScroller.scrolling(function(){//Listening for scrolling events
            console.log('scrolling');
        });

Answer №1

Success! This solution seems to have solved the issue.

All code that relies on DOM elements has been moved into a function that executes after all DOM Content is loaded. Additionally, the wheel event listener has been added to the specified element.

var myScroller;

function Scroller(el) { //Constructor
    this.el=el;
    this.el.addEventListener('wheel', this.scrolling, { passive: true })
}

Scroller.prototype.scrolling = function(event){ //
    console.log(event);
}

window.addEventListener("DOMContentLoaded", function() {
  let el = document.getElementById('myElement');
  myScroller=new Scroller(el);
})
<div style="width:100px;height:100px;border:1px solid black" id="myElement"></div>

Below showcases the same functionality using three different strategies, each resulting in a unique version of this within the scroll function. All methods are effective, with potential arguments for and against each. Ultimately, the choice comes down to practicality.

var myScroller;

function Scroller(el) { //Constructor
    this.el=el;
    this.el.addEventListener('wheel', this.scrolling, { passive: true })
    document.getElementById('element2').addEventListener('wheel', this.scrolling2.bind(this), { passive: true })
}

Scroller.prototype.scrolling = function(event){ //
    console.log(`this is myElement: ${this == document.getElementById('myElement')}`)
}

Scroller.prototype.scrolling2 = function(event){ //
    console.log(`this is myScroller: ${this == myScroller}`)
}

window.addEventListener("DOMContentLoaded", function() {
  document.getElementById('element3').addEventListener('wheel', (event) => { console.log(`this is window: ${this == window}`) }, { passive: true })
  let el = document.getElementById('myElement');
  myScroller=new Scroller(el);
})
<div style="width:100px;height:100px;border:1px solid black" id="myElement"></div>
<div style="width:100px;height:100px;border:1px solid black" id="element2"></div>
<div style="width:100px;height:100px;border:1px solid black" id="element3"></div>

The following can be considered the most elegant approach as it binds instantiations of anonymous DOM manipulation functions to DOM objects.

let attachScroller = (element) => element.addEventListener('wheel', function(event) { console.log(this.id) }.bind(element), { passive: true })

window.addEventListener("DOMContentLoaded", function() {
  attachScroller(document.getElementById('myElement'))
  attachScroller(document.getElementById('element2'))
})
<div style="width:100px;height:100px;border:1px solid black" id="myElement"></div>
<div style="width:100px;height:100px;border:1px solid black" id="element2"></div>

Answer №2

The issue lies in this section:

myScroller.scrolling(function(){//Detection of scroll
  console.log('scrolling');
});

Here, you are calling a callback function. Your addEventListener is not invoking the callback, but rather it's triggering your scrolling function with a WheelEvent instead of a function. The only instance where it is called as a function is in the preceding code snippet.

A simpler approach would be:

mousewheelListen=function(){
  this.el.addEventListener('wheel', event => Scroller.prototype.scrolling.call(this, event));
}

Scroller=function(el){//Initializer
  this.el=el;
  mousewheelListen.call(this);
}
Scroller.prototype.scrolling=function(){//Detection of scroll
  console.log('scrolling');
}

var el=document.getElementById('myElement');
var myScroller=new Scroller(el);

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

Encountered an issue while attempting to import a package in ES6: 'Module specifier "vue" could not be resolved'

As I dive into Vue tutorials, I find myself facing a challenge in importing Vue into a .js file and then linking this file to my index.html. The script importation in my index.html looks like this: <script src="./js/main.js" type="module"></scrip ...

Guide on triggering background notifications to display in the foreground of an Angular Firebase application using Angular 9 webapp

I've been using Angular Firebase for push notifications and everything is going smoothly with foreground messages. However, I encountered an issue when trying to handle background messages by adding a 'setBackgroundMessageHandler' call in my ...

What is the process for inserting a string into an array at a specified position?

I need to input a string into an array at a specific position, with all the preceding positions being converted to empty strings if they do not exist. For example: var array = []; // I want to insert 'hello' at index 2 The array should now loo ...

How come JavaScript variables are able to persist on JQuery Mobile multi-page templates on desktop browsers, but not on mobile browsers?

My website was created using the jQuery Mobile multi-page template. While testing it on Chrome desktop, I noticed that my JavaScript variables (comics and checkedItems) retain their values when navigating between pages. However, on mobile devices, these ar ...

Issues with vue-cli eslint failing to capture errors

I'm having trouble setting up eslint for my new vue cli project. I can't seem to get it to catch the errors I intentionally add, even though it passes without any issues. Any suggestions on what might be going wrong? vue.config.js devServer: { ...

The presence of certain characters is leading to problems in the console

Similar Question: Escaping a String for JavaScript Usage in PHP? The characters in my text are causing errors. When I input special characters such as: !\"$%^&()-=\'.,:;/?#~/\\>< An error saying "Syntax error ...

What is the best way to link objectID, name, phone, and other fields from one collection(schema) to a different one in MongoDB

Is there a way to create a form for customizing cakes where the user's information is automatically saved in the database along with their cake preferences? I'm looking to mimic the order model used in e-commerce websites, but I'm strugglin ...

Transmit information to the controller using jQuery in a C# MVC environment

Here is my jQuery script code snippet. The script works perfectly and stores the data array/object in a variable called dataBLL. var dataBLL = []; $('#mytable tr').each(function (i) { dataBLL.push({ id: $(this).find('td:eq(0)').text( ...

What is the best way to access elements from the following page once you have switched pages using a JavaScript command?

driver.execute_script("paginateGayrimenkul(2);") this line of code is supposed to navigate the webdriver to the second page of the website. However, even after executing this code, when I look for elements on the page, I still receive elements fr ...

Challenges encountered during the updating of nodes in 3D force graphs

I am currently developing an application where users can utilize a dat.gui menu to customize their Three.js animation. Specifically, I am implementing the 3d-force-graph library. Whenever a user makes a change, the following steps are taken: Swap out the ...

Retrieve binary data of an image from an API and render it on an HTML page

I have been working on storing images in a MongoDB database and trying to display the response I receive from an Express API as an image on the client side. The image source URL looks like this: src="/image/data/5a44dde172aa021d107e7d33" When I try to wr ...

"Facing an issue with Django paginator where redirecting to the same page after submitting a form in views.py is not

I have encountered an issue where, after submitting a form that fetches a view from views.py, the page reloads back to page 1 due to the paginator. My goal is for the browser to remain on the same page upon form submission. The error message I am receiving ...

Webpage created from scratch encounters technical difficulties on mobile device browser

My website seems to be getting stuck at the beginning of a section, particularly on mobile browsers. You can check out the website here <section class="home-slider owl-carousel"> <div class="slider-item" style="background-image: url(images/bg ...

Find the matching ID and consolidate all the information under one single ID

I am looking to merge objects with the same title and consolidate their data into a single object. new = [{ "data": [{ "displayName": "Peter pvt ltd", "name": "Peter Zon"}], "title&quo ...

Utilizing the {{value}} parameter within the JavaScript block of the thinger.io HTML gadget

When creating an HTML widget with JavaScript code on the thinger.io Dashboard, you can easily include data from the "thing" by using {{value}} within HTML tags. However, incorporating this data into a JavaScript block poses a challenge. Example of a Pure ...

What is the best approach to managing data organization within a websocket API?

We currently have a ReactNative page that displays live data using a Websockets based API. We want to provide users with the option to sort the data based on their selected field. What is the best way to implement data sorting? I am considering two possi ...

What could be causing the multifiles uploader to fail in uploading files?

I have been attempting to create a multiple files uploader with sorter connected to a database on my website. However, whenever I try to upload some files, the uploader sends me several notices. Notice: Undefined index: media in /var/www/mediasorter/mediau ...

What is the best approach to implement a basic image upload functionality?

I have a vision for my new website where users can upload an image with the click of a button, store it locally on one page and then retrieve its absolute URL to share on forums or other websites for preview purposes. While I've managed to create a fu ...

How come the "colspan" attribute is not functioning properly in my table?

Check out the simple table form I created on jsfiddle. Here is the code snippet: <table> <tr> <td class="field_label">name</td> <td>*</td> <td> <input type="text"> ...

Add and condense sub-row

I am struggling to make the child row collapse and append when clicking on the parent row. It seems like my code is not working properly. Can anyone offer some guidance or assistance? This is the code for the parent row: $j(document).ready(function(){ $ ...