Building on David Walshes MooTools Tip: Event.stop

David Walsh shared a tip on how he handles firing events on an element without user input to trigger the event. I\’m going to build on that by sharing how I would handle it.

Problem

The issue is that usually an event is added and the default behavior is disabled.

$(\'myLink\').addEvent(\'click\',function(e) {
    e.stop();
    //do stuff
});

And if you just so happen to need to trigger the event manually, like so:

$(\'myLink\').fireEvent(\'click\');

You\’ll get an error that the stop method doesn\’t exist. This is because you\’re just firing the function and an event argument is not being passed into the function.

Now, lets say you have a class and you wanted to manually execute a method that\’s being attached to an event. An error would also occur in this case.

var myClass = new Class({
    // ... some code here..

    // the click event function that is attached..
    clicky: function(e){
        e.stop();
        //.. do some clicky stuff
    }

});

// create instance of class
var instance_of_myClass = new myClass();

// firing clicky function
instance_of_myClass.clicky(); // results in error because stop() does not exist

Solution

Here\’s how you can solve both problems, and I learned this from Mark Obcena. This is very useful if you don\’t want to modify the classes code or extend it. Pass in a dummy object with an empty stop function:

// this will fire the click event without an issue
$(\'myLink\').fireEvent(\'click\', {stop:$empty});

// this too will fire the clicky function on the instance without an issue
instance_of_myClass.clicky({stop:$empty});

Tada! Thanks David and Mark!

9 thoughts on “Building on David Walshes MooTools Tip: Event.stop”

  1. thank you soooooooooooooo much. really good job and nice idea.
    btw, landed here by googling “mootools fireevent e.stop is not a function”.

  2. fantastic post, very informative. I wonder why the opposite experts
    of this sector don’t notice this. You should proceed your writing. I am confident, you have a great readers’ base already!

Leave a Reply

Your email address will not be published. Required fields are marked *