Creating custom events in a JavaScript constructor function

Just beginning to learn JavaScript. I have a custom function that I want to assign events to in the constructor.

var myFunction = function(){
/*
some code
*/

}
myFunction.prototype.add=function(){

/*
adding item*/

}

Now I am looking to add an event to the constructor

var newFunction = new myFunction;

myFunction.onadd(function(){
/*execute on adding item*/
});

I will need to attach it with various functions multiple times.

What is the best way to add events and call the functions?

Answer №1

In this explanation, the concept is divided into two main parts. The first part, labeled as on, is responsible for gathering handlers and event triggers. Specifically, in your scenario, the event trigger is identified as add.

Within the on function, the handlers are organized based on the assigned event:

function yourConstructor(){
  this.events = {};
}

yourConstructor.prototype.on = function(eventName, handler){
  // A new property named `eventName` is created within `this.events`,
  // While an array stores all associated handlers for that particular `eventName`.
}

The second part involves executing specific handlers tied to a function, such as add:

yourConstructor.prototype.add = function(){
  // Perform the desired operations of the add function
  // Subsequently, execute all handlers stored in the `this.events.add` array.
}

Answer №2

Creating your own eventing system is an option, but I would recommend utilizing existing libraries that are already available. Here are a few good options:

If you're interested in seeing how microevent works, check out this jsFiddle example.

function Person(name) {
    this.name = name;
}

Person.prototype.sayName = function () {
    alert('My name is ' + this.name);
    this.trigger('nameSaid');  //trigger the nameSaid event
};

//Apply the MicroEvent mixin to make Person instances observable
MicroEvent.mixin(Person);

//Create a new Person instance
var o = new Person('John Doe');

//Listen for the nameSaid event
o.bind('nameSaid', function () {
    alert(this.name + ' just said its name!');
});

o.sayName();

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

Immersive Visual Symphony through Dynamic Multi-Layered

My goal is to create captivating animations for my multiple background images. Here's the CSS code I've come up with: .header { background-image: url('/img/cloud2.png'), url('/img/cloud3.png'), url('/img/cloud1.png&apos ...

What could be the reason behind the malfunctioning of $.getjson?

I've been facing issues trying to access remote json data. Initially, I resorted to using as a temporary fix but it's no longer serving the purpose for me. As of now, I am back at square one trying to resolve why I am unable to retrieve the remo ...

Utilizing jQuery's multiple pseudo selectors with the descendant combinator to target specific elements

My code includes the following: <div class="a"><img></div> and <div class="b"><img></div> I want to dynamically enclose img tags with a div and utilize $(":not('.a, .b) > img") for ...

What could be causing the error message to appear stating that each list item must have a unique key when utilizing react-bootstrap in Nextjs?

My file currently contains keys for each child component, but it is still raising an error internally. I am unsure if I can resolve these issues on my own. export default function SecondaryNav(props:NavItems) { const router = us ...

Struggling to traverse through intricate layers of nested objects in React and showcasing them without going crazy

Dealing with an API that returns data structured in deeply nested objects has been a challenging task. The goal is to extract specific data from these nested objects and then display them within a React project. Despite numerous attempts, finding a simple ...

Jest and Enzyme failing to trigger `onload` callback for an image

I'm having trouble testing the onload function of an instance of the ImageLoader class component. The ImageLoader works fine, but my tests won't run properly. Here's an example of the class component: export default class ImageLoader extend ...

Retrieving PHP data with jQuery

Isn't it interesting that I couldn't find anything on Google, but I believe you can assist me. I have a Table containing different accounts. Upon clicking on a specific row, I want another table related to that account to slide in. This secondary ...

The function canvas.toDataURL() is not recognized - error originating from a node-webGL wrapper

I am currently working on converting client-side volume rendering code in the browser to server-side rendering using pure JavaScript. On the server side, I am utilizing node-webgl. My objective is to send the server's canvas content to the client so ...

Guide on implementing two submission options in an HTML form using JavaScript

Currently, I am working on a form that includes two buttons for saving inputted data to different locations. However, I am facing an issue with the functionality of the form when it comes to submitting the data. Since only one submit function can be activa ...

Metronome in TypeScript

I am currently working on developing a metronome using Typescript within the Angular 2 framework. Many thanks to @Nitzan-Tomer for assisting me with the foundational concepts, as discussed in this Stack Overflow post: Typescript Loop with Delay. My curren ...

Is there a bug in Safari 8.0 related to jQuery and backslashes?

I am using Mac OS 10.10 Yosemite and Safari 8.0. Attempting to read an XML (RSS) file: <content:encoded>bla bla bla</content:encoded> The Javascript Ajax method I am using is: description:$(valeur).find('content\\:encoded&apo ...

Having trouble accessing the `then` property of undefined while utilizing Promise.all()?

An issue has occurred where the property 'then' of undefined cannot be read: getAll(id).then((resp) => {...} ... export function getAll(id){ all([getOne(id), getTwo(id)]); } ... export all(){ return Promise.all([...arg]) } I' ...

Expanding the outer div with Jquery's append() function to accommodate the inner div elements perfectly

I am facing an issue where my outer div does not expand automatically to fit the elements I append inside it using jQuery. The structure of my div is as follows: <div class="well" id='expand'> <div class="container"> < ...

Strange alignment issues occurring solely on certain PCs

Currently, I am in the process of developing a website for a client who has requested that it be an exact replica of the mockup provided. However, I have encountered some issues with the headers and certain divs that contain background elements. Surprising ...

What is the method for determining the level based on the provided experience points?

I've created a formula that can calculate experience based on specific levels and another formula that calculates the level based on given experience. However, there seems to be an issue with the second function as it is not returning the expected val ...

Issue with Observable binding, not receiving all child property values in View

When viewing my knockout bound view, I noticed that not all values are being displayed. Here is the script file I am using: var ViewModel = function () { var self = this; self.games = ko.observableArray(); self.error = ko.observable(); se ...

Steps for storing div content (image) on server

Currently in the process of developing a web application that allows users to crop images. The goal is for users to have the ability to email the URL so others can view the cropped image, ensuring that the URL remains active indefinitely by storing every c ...

I'm facing a challenge where Multer is preventing me from showing images in my React app

Hi there, I'm currently facing an issue where I am using multer to save files on my server and store their path in mongodb. However, I am struggling to display them on my React application. Any assistance would be greatly appreciated. Thank you in ad ...

How can I remove a dynamically added <tr> element using jQuery?

I insert the <tr> into the <tbody> for (var i = 0 ;i < 12 ;i++){ $(`<tr><td>test</td></tr>`).appendTo('#songsTbody'); } within this HTML structure. <tbody id="songsTbody"> </tbody> ...

Error: Attempting to create a Discord bot results in a TypeError because the property 'id' is undefined

While working on a basic Discord bot, I encountered an issue when running the -setcaps command. The error message I received was: TypeError: Cannot read property 'id' of undefined. I'm unsure about what might be causing this error. Any a ...