Creating Custom Events using javascript / Jquery ~ Web CodeHelpers

Creating Custom Events using javascript / Jquery


The older approach to creating events uses APIs inspired by Java. The following shows an example:
// Create the event.
var event = document.createEvent('Event');

// Define that the event name is 'build'.
event.initEvent('build', true, true);

// Listen for the event.
document.addEventListener('build', function (e) {
  // e.target matches document from above
}, false);

// target can be any Element or other EventTarget.
document.dispatchEvent(event);

Events can be created with the Event constructor as follows:
var event = new Event('build');

// Listen for the event.
elem.addEventListener('build', function (e) { ... }, false);

// Dispatch the event.
elem.dispatchEvent(event);

0 comments :

Post a Comment

Subscribe updates via Email