Reputation: 4619
I have implement three jQuery-like functions for controling my custom events (i can't using jquery in my project :-():
var Events = {
on: function(evt, fn) {
document.addEventListener(evt, fn);
},
off: function() {
document.removeEventListener(evt, fn);
},
trigger: function(evt, params) {
var event; // The custom event that will be created
if (document.createEvent) {
event = document.createEvent("HTMLEvents");
event.eventName = evt;
event.initEvent(evt, true, true);
event.data = params;
window.dispatchEvent(event);
} else {
event = document.createEventObject();
event.eventName = evt;
event.eventType = evt;
event.data = params;
window.fireEvent("on" + event.eventType, event);
}
}
}
When i using my observer implementation i have:
Events.on('custom', function(e) {
console.log(e.data); // output [5,10,15]
});
Events.trigger('custom', [5, 10, 15]);
But i need modify my trigger function to call listener with additional parameters after event object. Something like jquery.trigger() function with extraParameters attribute. For my example:
Events.on('custom', function(e, a, b, c) {
console.log(a, b, c); //output [5,10,15]
});
Events.trigger('custom', [5,10,15]);
Upvotes: 1
Views: 437
Reputation: 4776
var event = new CustomEvent('build', { 'detail': 'test' });
// Listen for the event.
document.addEventListener('build', function (events) {
console.log(events.detail)
}, false);
// Dispatch the event.
document.dispatchEvent(event);
In this way you can pass data to custom created event
EDIT:
if (window.CustomEvent) {
var event = new CustomEvent('my-event', {detail: {some: 'data'}});
} else {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('my-event', true, true, {some: 'data'});
}
this is jquery equivalent to trigger
Upvotes: 1