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?

1 Answer 1

5

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(){}
});
5
  • 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
    Commented Sep 24, 2012 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. Commented Sep 24, 2012 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
    Commented Sep 24, 2012 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. Commented Sep 24, 2012 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. Commented Sep 25, 2012 at 12:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.