Define custom event - javascript

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.

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").

You're lumping together two different points:
how events work on general, and
how a browser environment dispatches events related to user action.
For the first point, I'll quote from another answer of mine:
In JavaScript, a custom event is simply a message, broadcast to all event listeners, that says, "Attention everyone: event X just happened!" Any listener that cares about that event can then run some function.
That's how events work in JavaScript. You set up listeners, and later something triggers the event. The trigger acts as a message to the listeners, telling them to run.
I've just said something triggers an event: we'll call that thing the initiator of the event. With custom events, the initiator is always other JavaScript code that you write (or that comes from a library, etc.). However, with native events the initiator is the browser itself. There is no way for JavaScript to control how the browser chooses to dispatch events.
The best you can do is listen for native browser events and then have those listeners dispatch custom events themselves.

For people who are wondering (like I did in the last 2 years) you can create a custom event (using pure javascript) as explained below:
var myEvent = new Event('myEvent');
and then you can use it like this:
document.querySelector('button').addEventListener(myEvent, function () {});
Simple Usage Example DEMO
Let's say we have a variable called bgColor and we want to change background color of 5 buttons, color of a paragraph and border color of an input anytime the bgColor value changes AND we don't want to use an interval to check on the value change and we also don't want to repeat the same code over and over again anytime the variable changes.
First we need to define our variables:
var bgColor='red',
eventName = 'bgColorChanged';
Then we need to listen for 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])
}
//----------------------------
}
}
Now we can listen for 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);
}
//-----------------------------------
}
Now we can fire our event like this:
dispatchEvent(eventName);
Now that everything's ready we just need to change the value of bgColor and just fire the event and let our system do the work.
bgColor='blue';
dispatchEvent(eventName);

Related

how to add custom events to svg.js

I'm testing svg.js library, and have found problems declaring custom events. Here is the fiddle. Clicking on the first circle should change the color and it works:
circleOne.click(function() {
this.fill({ color: '#f06' })
})
Clicking the second circle should fire the custom event, but it doesn't:
var circleTwo = SVG.select('circle.circle-01');
circleTwo.on('myevent', function() {
alert('ta-da!')
})
function testMe() {
circleTwo.fire('myevent')
}
Changing .fire to .event doesn't help either. Any suggestions? Thanks in advance.
You never use testMe function to fire your event :)
Browser defined events are already fired when an event happens, for the custom event you have correctly defined what happens (alert) when it fires but if you intend it to go off at some point you have to fire it. You also made trigger function but you never used it.
You can fire it on browser defined triggers BUT then simply rather use those events, don't define custom.
Custom events are intended for different use cases. For example, you detected an object is untouched for 10 sec and you wanna notify some other part of the code to react to it. That event is not defined by default, you define it and have custom code checking that fire the event when the condition is met.
Try firing your event on for example click event or simply for testing put this at the end of the scrypt:
testMe();
Now you have fired your custom event when the script loads to that point and executes trigger function.

Click event listener

I'm working on an Electron-based application, and I don't have much experience with it or JavaScript or Node.js. Currently, I just want to close a window by a click on a button.
close.addEventListener('click', function () {
ipc.send('close-main-window')
})
This totally works! I am just confused with why it works. From what I understand, the first argument in addEventListener is just any arbitrary string. However, I don't specifically write anything to handle a 'click'. This should mean it's built in functionality, I think. Is this part of JavaScript, Node.js, or Electron? And where in the documentation can I find a list of built in events?
JavaScript has the function addEventListener which adds an event listener (surprise, surprise) to an element. The element in which the listener is applied to now listens for an event, a string passed into the function (in this case click). Once the event is triggered (in this case when a user clicks on the element), it will execute the callback, which is the function you declared. So, consider this:
element.addEventListener("click", function() {
console.log("hello!");
});
This will log hello every time element is clicked.
You can read more at the Mozilla's Documentation. Here's a list of all the available events.
The first argument is string which represent the event type.
I think internally it works like this
var event = new Event('click');
where Event is an event object & click is already a predefined event of javascript

Access all event listeners in Javascript

I want to do something like this:
function('string', function2(){})
where I leave the to user to write what he wants in the string parameter and than execute function2.
The catch is here: string is an event listener. When the user writes click, I want to call onClick(), when the user writes mouse I want to call onMouseOver and so on.
I have in mind doing something with case, but how can I access all event listeners?
You should use addEventListener.
element.addEventListener("string", function() {}, false);
However, in the case of IE <= 8, you will need to use attachEvent as it does not follow the standard:
element.attachEvent("string", function() {});
Finally, as kybernetikos mentions in his comment, you can then use a simple dictionary to map mouse to mouseover.
If you wish to fire events, you should use dispatchEvent.
If you add the event listeners using the old model (i.e. elem.onclick = function(){ /* */ };), you can use
elem['on' + event]();
Keep in mind that this only fires the event listeners, but doesn't create an event (e.g. it won't bubble).
If you won't to create a event, which fires event listeners added using addEventlistener, and bubbles, and does all things a real event does, you must
Create your event using event constructors: Event or CustomEvent
Fire it with dispatchEvent
See MDN page for more information and examples.
you can use .trigger to do this. Check out this example in jsfiddle. type "dblclick" in the input box.
http://jsfiddle.net/jspatel/Suj4H/1/
<input id="writehere"> </input>
$('#writehere').dblclick(function() {
alert ('dblclick');
});
$('#writehere').bind('keypress', function(e) {
if(e.keyCode==13){
$(this).trigger( $(this).val() );
}
});

need help understanding this code

this code in book jQuery in action page 131
i don't understand
.trigger('adjustName');
what is adjustName
and Simple explanation for trigger()
thanks :)
$('#addFilterButton').click( function() {
var filterItem = $('<div>')
.addClass('filterItem')
.appendTo('#filterPane')
.data('suffix','.' + (filterCount++));
$('div.template.filterChooser')
.children().clone().appendTo(filterItem)
.trigger('adjustName');
});
It is a string, the name of a custom event you defined.
E.g. it would trigger the event handler bound by:
el.bind('adjustName', function(){...});
For more information I suggest to have a look at the documentation:
Any event handlers attached with .bind() or one of its shortcut methods are triggered when the corresponding event occurs. They can be fired manually, however, with the .trigger() method. A call to .trigger() executes the handlers in the same order they would be if the event were triggered naturally by the user.
Without knowing the context of the code, I would say that calling .trigger() here has no effect, as it is called on the cloneed elements and the event handlers are only cloned if true is passed to clone.
Maybe the original jQuery manual could be helpful?
Description: Execute all handlers and
behaviors attached to the matched
elements for the given event type.
It allows you to trigger, or run, an event. For instance if you wanted the code to mimic the clicking of a button, you could write....
$("#myButton").trigger('click');
This would then run exactly as if you had clicked the button yourself.
'adjustName' is a custom event. So the trigger function is running that custom event. The custom event is assigned using the jQuery bind function.
$("#someElement").bind('adjustName', function() {/* Some Code */});
You might create a customer event for clarity. Perhaps your application opens a document, so you might want an event called 'openDocument' and 'closeDocument' assigned to the element containing the document.

Intercept javascript event

Here's what I'm trying to do :
I have a page with some links. Most links have a function attached to them on the onclick event.
Now, I want to set a css class to some links and then whenever one of the links is clicked I want to execute a certain function - after it returns , I want the link to execute the onclick functions that were attached to it.
Is there a way to do what I want ? I'm using jQuery if it makes a difference.
Here's an attempt at an example :
$("#link").click(function1);
$("#link").click(function2);
$("#link").click(function(){
firstFunctionToBeCalled(function (){
// ok, now execute function1 and function2
});
}); // somehow this needs to be the first one that is called
function firstFunctionToBeCalled(callback){
// here some user input is expected so function1 and function2 must not get called
callback();
}
All this is because I'm asked to put some confirmation boxes (using boxy) for a lot of buttons and I really don't want to be going through every button.
If I understand you correctly, is this wat you wanted to do..
var originalEvent = page.onclick; //your actual onclick method
page.onclick = handleinLocal; //overrides this with your locaMethod
function handleinLocal()
{ ...your code...
originalEvent ();
// invoke original handler
}
I would use jQuery's unbind to remove any existing events, then bind a function that will orchestrate the events I want in the order I want them.
Both bind and unbind are in the jQuery docs on jquery.com and work like this...
$(".myClass").unbind("click"); // removes all clicks - you can also pass a specific function to unbind
$(".myClass").click(function() {
myFunctionA();
myFunctionB($(this).html()); // example of obtaining something related to the referrer
});
An ugly hack will be to use the mousedown or mouseup events. These will be called before the click event.
If you can add your event handler before the rest of handlers, you could try to use jQuery's stopImmediatePropagation

Categories