Defining a custom event

I want to know how to define a custom event , but not as stated on the net! let me illustrate:

On the jQuery website, under Custom Events View, it teaches how to create a custom event in your code:

eg.

$(document).on('myEvent',function(){
    alert('Hello World');
});

      

then in the event you will call:

$(document).trigger('myEvent');

      

Well, no problem. go further, I must give you another example:

Question:

let's say we have defined:

$.fn.myEvent=function(callback){
    $(document).bind('contextmenu',this,callback);
};

      

so we can use it like:

$(document).myEvent(function(){
    alert('Hello World');
});

      

my question here is how can we define "myEvent" so that we can use it like:

$(document).on('myEvent',function(){
    alert('Hello World');
});

      

with functionality $(document).myEvent();

so that we can pass a callback function to it without an actual trigger

event?

More Explanation:

for example, when we call $(document).on('click');

, we don't really need to fire the click event elsewhere, for example $(document).trigger('click')

, to make it work, so whenever it click

happens, the function fires. I want to have an event listener for "myEvent" so that when the conditions are met, the function will fire.

In another word (as mentioned below in the comments), I want to know if there is a way to allow jQuery to treat "myEvent" as if it were one of the default events (click, mousemove, submit, etc.).

Any answer or idea is much appreciated.

+3


source to share


3 answers


For people who are wondering (I have been doing this for the last 2 years for example), you can create a custom event (using pure javascript) as described below:

var myEvent = new Event('myEvent');

      

and then you can use it like this:

document.querySelector('button').addEventListener(myEvent, function () {});

      

An example of a simple use of DEMO

Let's say we have a variable called bgColor

and we want to change the background color of 5 buttons, the paragraph color and the input border color anytime the value changes bgColor

, and we don't want to use spacing to check for the value change, and we also don't want repeat the same code over and over anytime the variable changes.

First we need to define our variables:

var bgColor='red',
    eventName = 'bgColorChanged';

      

Then we need to listen to the event:



function Listen(elems,eventName,callback){

    var event=new Event(eventName); //create the custom event

    for(var i=0, elemsLength=elems.length; i < elemsLength; i++){ //iterate over the selected elements

        elems[i].addEventListener(event,callback); //add event listener for our custom event

        elems[i][eventName]=event; //store the event

        //store the element
        if(window.affectedElems){
            window.affectedElems.push(elems[i])
        }
        else{
            window.affectedElems=[];
            window.affectedElems.push(elems[i])
        }
        //----------------------------

    }
}

      

We can now listen to our custom event like this:

Listen(document.querySelectorAll('button'),eventName,function(){
    this.style.backgroundColor=bgColor;
});

      

Then we need a function to dispatch / fire our event:

function dispatchEvent(eventName) {

    var event=document.createEvent("HTMLEvents"), //defining the type of the event

    elems=window.affectedElems; //getting the stored elements

    //iterating over each element and dispatching the stored event
    for(var i=0, elemsLength=elems.length; i < elemsLength; i++){
        event.initEvent(elems[i][eventName], true, true);
        event.eventName = eventName;
        elems[i].dispatchEvent(event);
    }
    //-----------------------------------
}

      

We can now fire our event like this:

dispatchEvent(eventName);

      

Now that everything is ready, we just need to change the value bgColor

and just fire the event and let our system do the work.

bgColor='blue';
dispatchEvent(eventName);

      

0


source


I want to have an event listener for "myEvent" so that when the conditions are met, the function will fire.

How would the engine know what "terms" you mean? No, "custom events" are called custom events because they are not triggered natively (by some lower-level action), but by custom code.
You can fire a custom event whenever you see the matching condition you are looking for.



About the definition, $.fn.myEvent

you can see how shortcuts are created for your own events (where it name

will be "myEvent"

).

+2


source


You are merging two different points:

  • how events work on common, and
  • how the browser environment dispatches events related to user action.

In the first paragraph, I will quote from another my answer :

In JavaScript, a custom event is simply a message sent to all event listeners that says "Attention everyone: event X just happened!" Any listener that cares about this event can then run some function.

How events work in JavaScript. You set up listeners and then something raises an event. The trigger acts as a message to listeners, telling them to fire.

I just said that something triggers an event: we'll call it the event trigger. With custom events, the initiator is always other JavaScript that you write (or that comes from a library, etc.). However, with its own events, the browser itself is the initiator. JavaScript has no control over how the browser chooses to dispatch events.

The best you can do is listen for native events in the browser, and then those listeners themselves dispatch their own events.

+2


source







All Articles