问题
I am trying to figure out how to properly create and fire events in JavaScript, so in the process of learning ran into this page:
https://developer.mozilla.org/en-US/docs/DOM/document.createEvent
Which at the top informs me of the following:
The createEvent method is deprecated. Use event constructors instead.
Googling JS event constructors was not very fruitful - topics talking about constructors in general, but not what I am looking for. Could somebody please explain to me what are the event constructors and provide a good example of their usage?
回答1:
From https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent:
It seems that events are now encapsulated in a class called CustomEvent. You can think of the old document.createEvent as a factory method that returns an event object. Now, instead of using document.createEvent to create the object, you now have access to create the object directly.
//this is the new way
var my_event = new CustomEvent('NewEventName');
var my_element = document.getElementById('TargetElement');
my_element.dispatchEvent(my_event);
is the replacement for
//this is the old way
var my_event = document.createEvent('NewEventName');
var my_element = document.getElementById('TargetElement');
my_element.dispatchEvent(my_event);
回答2:
You want to use addEventListener()
https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener
Here's my library code for attaching events, I found these on stackoverflow and put them inside of my app global namespace:
var app={}
app.listenEvent=function(eventTarget, eventType, eventHandler) {
if (eventTarget.addEventListener) {
eventTarget.addEventListener(eventType, eventHandler,false);
}
else if (eventTarget.attachEvent) {
eventType = "on" + eventType;
eventTarget.attachEvent(eventType, eventHandler);
}
else {
eventTarget["on" + eventType] = eventHandler;
}
}
app.cancelEvent=function(event) {
if (event.preventDefault)
event.preventDefault()
else
event.returnValue = false;
}
app.cancelPropagation=function(event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true; }
}
So to add an listen for an event:
app.listenEvent(document.aform.afield, 'focus', function(){console.log(arguments)} )
These functions are great, they work in all browsers.
来源:https://stackoverflow.com/questions/15951468/what-is-a-good-example-of-using-event-constructors-in-js