Gaining entry to a JavaScript prototype method

I'm currently working on a prototype function called event.

Prototype

Func("input_element_id").event("keyup",function(){
    alert("Works on keyup in an Input!");
}

Func.prototype= {
    keyup: function(func){
         //adding event listener and callback using func
    },
    event: function(e,func) {
         //what to do here to call function "keyup"
    }
};

The prototype name is stored in the variable e. Now, I'm trying to figure out how to call that particular function using the variable name.

I am experimenting with this approach in order to allow passing "keyup keydown" as arguments to add keyup and keydown listeners simultaneously, instead of calling each prototype function individually.

Your insights would be greatly appreciated. Thanks!

Answer №1

const FunctionObj = function(elem){
  this.elem = elem;
};

FunctionObj.prototype = {
    addKeyupListener: function(handler){
      this.elem.onkeyup = handler;
    },
    addEventListener: function(event, handler){
        switch(event){
            case 'keyup':
              return this.addKeyupListener(handler);
            break;
        }
    }
}

http://jsfiddle.net/YDekw/

Answer №2

To access the receiving object, use the keyword this.

this.keypress(func);

If you have a modern browser or an ES5 shim installed, here is how you can achieve this:

e.split(" ").forEach(function(item) {
    this[item](func);
}, this);

Keep in mind that it refers to the object being used with the dot operator and can vary based on context. For instance:

var obj = new Obj("input_id");
window.action = obj.action;
window.action(); // in this case, 'this' refers to window

Answer №3

A proven method to reach this goal is through:

events: function(events,func) {
            this[events](func);
        }
    }

Credit goes to CrazyTrain, as highlighted in the Comments.

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

Error encountered with Passport js Local Strategy: The LocalStrategy necessitates a verify callback function

Encountering Passport JS Local Strategy Error with Node & Express I have successfully implemented OAuth 2 for Google authentication using Passport in my project. However, I am facing an error with the Local Strategy of Passport and I can't seem to fi ...

Having some trouble implementing the functionality of hiding a data series in HighCharts using `{ data: [], visible: false }` notation

I am currently working on creating a graph that displays multiple series obtained from JSON data in a MySQL database. My goal is to have the graph show only one series initially. Thankfully, HighCharts offers an option to achieve this as demonstrated below ...

Tips for enabling autofocus in mat-select列表。

I am working on an angular project where I am using Angular Material and a mat-select element. In my form, the mat-select is the first element, and I want to set auto-focus on it when the page loads. However, I have been facing some difficulties achieving ...

Display Quantity of Current Website Visitors

Similar Question: how to track website visitors using java script or php I am looking to retrieve the current number of viewers on a webpage that has an embedded stream. Is there a method to accomplish this utilizing PHP and AJAX, in order to display ...

execute a function for every regex match found within a string

When working with WordPress or PHP in general, I came across this interesting recommendation for email obfuscation, and I would like to: Convert email addresses to mailto links Encode the mailto links using str_13() Decode them client-side using JavaScri ...

Request successful but receiving no response text and content length is zero

let req = new XMLHttpRequest(); req.addEventListener('load', function (data) { console.log(data) }, false); req.open("get", "/bar.txt", true); req.send(); Feeling a bit perplexed at the moment, I can't seem to figure out what's going ...

What events precede and follow a keydown action in a Textarea field?

I need to prevent users from pressing function keys (F1, F2, etc.), the tab key, and any other characters from being added. The code below is supposed to achieve this on my website but it's not working. document.getElementById("code").addEventList ...

Scroll the content of a div to the bottom using JavaScript

I'm facing a situation with my code: function scrollme(){ dh=document.body.scrollHeight ch=document.body.clientHeight if(dh>ch){ moveme=dh-ch window.scrollTo(0,moveme) } } However, I am looking for a way to make it scroll only within a specific d ...

Encountering an issue with resolving the module - Material-UI

I am encountering an issue when trying to import a component from 'Material-Ui'. I am currently working with React and Webpack. My goal is to utilize the "Card" component (http://www.material-ui.com/#/components/card). The import statement for C ...

Having trouble bringing my custom-built Angular module into my Angular application

Currently considering the utilization of this Yeoman generator as a starting point for a small project that will contain several reusable form components to be published. The generator constructs a module and an example component, directive, pipe, and serv ...

The perplexing actions of Map<string, string[]> = new Map() have left many scratching their heads

I encountered an issue while trying to add a value to a map in my Angular project. The map is initially set up using the following code: filters: Map<string, string[]> = new Map(); However, when I attempt to add a value to this map, it starts displa ...

Confusion surrounding asynchronous functions in Node.js

When handling routes or endpoints with multiple operations, I often encounter scenarios where I need to perform additional actions. For instance, when deleting an item, it's necessary to also remove the related file from S3 along with deleting the col ...

Exploring the world of typescript with the power of ts-check

I'm having trouble figuring out how to work with a generic function using TypeScript's new ts-check feature. /** * @type {Reducer<IPoiState, any>} */ const poi = handleActions({ [ADD_BOOKMARK_START]: (state) => { return { ...sta ...

Click on the text within a paragraph element

Is there a way to retrieve the selected text or its position within a paragraph (<p>)? I'm displaying a text sentence by sentence using a Vue.js loop of paragraphs. <p class="mreadonly text-left mark-context" v-for="line in ...

Analyzing file data while uploading the file

Does anyone have a solution for extracting the content from an uploaded file in express/nodejs without saving it as a temporary file? I have code that successfully pipes the input to a filestream, but I'm struggling to deserialize the upload to a pla ...

Error Encountered: Unhandled Runtime Error in Next.js with Firebase - TypeError: Unable to access the property 'initializeApp' as it is undefined

It's baffling why this error keeps appearing... my suspicion is directed towards this particular file. Specifically, firebaseAuth={getAuth(app)} might be the culprit. Preceding that, const app = initializeApp(firebaseConfig); is declared in "../f ...

Interacting with a form input by triggering the onChange event

I am encountering a problem where I need to be able to select a radio button both onChange via keydown and mouse click. However, I am struggling with accessing both event parameters of the on keydown and on mouse click within the same function. As a result ...

Modifying the content within a DIV element

I want to make changes to my DIV. <div id="main"> <div id="one"> <div class="red"> ... </div> <img class="avatar" src="img/avatar1.jpg"/> <span class="name"> John < ...

Utilizing JavaScript For Loops for Code Repetition

Apologies for the ambiguous question title - struggling to articulate this properly. Essentially, I have some JavaScript code that I am looking to streamline by using a for loop. $('.q1').keyup(function () { if ($.inArray($(this).val().toLo ...

Tips for adding style to a group of SVG elements:

I currently have an array of .svg icons, each with unique properties that I need to customize: <svg width="24" height="24" viewBox="0 0 24 24"> ... </svg> import styled from 'styled-components'; import Github from 'assets/git ...