Garrick Cheung

Sharing what I know and learn about CSS, MooTools, Javascript, PHP and etc.

Building on David Walshes MooTools Tip: Event.stop

Posted on | December 29, 2009 | 5 Comments

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.

1
2
3
4
$('myLink').addEvent('click',function(e) {
    e.stop();
    //do stuff
});

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

1
$('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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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:

1
2
3
4
5
// 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!

Comments

5 Responses to “Building on David Walshes MooTools Tip: Event.stop”

  1. Dimitar Christoff
    March 10th, 2010 @ 8:36 pm

    nice… shame it does not help with older syntax of new Event(e).stop(); though :(

  2. l3bel
    April 8th, 2010 @ 9:58 am

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

  3. l3bel
    April 8th, 2010 @ 9:59 am

    and… bookmarked ;)

  4. Churro
    July 27th, 2010 @ 10:36 am

    Thank you very much for sharing this tip!

  5. Garrick
    August 12th, 2010 @ 11:03 pm

    @Churro: You’re welcome!

Leave a Reply





taking viagra woman Cheap Viagra
cheap gerneric viagra?