3

I am using Mootools and adding a click event to a link. I have added a function to an event with this:

$('addCallRoute').addEvent('click', addCallRoute); // Add button

The function contains this:

function addCallRoute(e) {
    console.log(e);
}

The function that fires the event (without an actual click)

$('addCallRoute').fireEvent('click');

The Problem: When I click on the link physically, e is defined. but when I programmatically fire the event, e is undefined. Why?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Kristian
  • 21,204
  • 19
  • 101
  • 176

1 Answers1

4

Because you're not actually/physically triggering an action but firing it remotely. This is how it works.

event normally contains all sort of information about the element from which the action was triggered.

Always check if event is defined before trying to use any methods on it. Or do this:

link.fireEvent('click', {
    stop: function(){}
});
Oskar Krawczyk
  • 3,492
  • 17
  • 20
  • thank you for your response. I can see that it doesn't *because* it is not physically triggering the event. but programmatically its still firing based on the event-attached element itself. so the question is *why* the argument does not still contain at least *some* event information when its not physically clicked – Kristian Sep 24 '12 at 20:26
  • The event data is not statically attached, that data will **only** be available if an actual action happens - like a click with a mouse. This is by design. – Oskar Krawczyk Sep 24 '12 at 20:33
  • that is interesting. can you point me to a resource that talks about this? i haven't been able to find one – Kristian Sep 24 '12 at 20:34
  • A specific resource no, it's simply the way Events in JavaScript work. Maybe start with MDN, you'll probably find some info regarding to DOM Events there. – Oskar Krawczyk Sep 24 '12 at 20:44
  • Think about events as an `action` (in this case, the click) followed by a `callback` (the function passed into `addEvent();`). The event information is only available if there is an action, and the callback is completely separate from that. All `fireEvent();` does is run the callback, irrespective of what actions had or hadn't happened. – Julian H. Lam Sep 25 '12 at 12:57