Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define custom event

I wanna learn how to define a custom event, but not exactly as it is said over the net! let me illustrate:

In the jQuery Website in the part Introducing Custom Events it teaches you how to create a custom event in your code:

e.g.

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

then on an event, you'll call:

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

Well, no problem until here. to go further I have to give you another example:

The Question:

let's say we've defined:

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

so we can use it as:

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

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

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

with the functionality of the $(document).myEvent(); so that we can pass a callback function to it without needing to actually trigger the event?

More Explanation:

for example, when we call $(document).on('click'); we don't actually need to trigger the click event elsewhere like $(document).trigger('click') in order to get it to work, so whenever click happens the function fires. I wanna have an event listener for "myEvent" so that when the conditions are matched, the function fires.

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

Any answer or idea is highly appreciated.

like image 329
Amin Jafari Avatar asked Aug 06 '26 17:08

Amin Jafari


1 Answers

I wanna have an event listener for "myEvent" so that when the conditions are matched, the function fires.

How would the engine know what "conditions" you mean? No, "custom events" are called custom because they are not natively trigged (through some lower-level action), but by custom code.
You may trigger a custom event whenever you see the condition matched that you're looking for.

About the definition of $.fn.myEvent, you might want to have a look at how the shortcuts for native events are created (where name would be "myEvent").

like image 163
Bergi Avatar answered Aug 08 '26 08:08

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!