Normally, if I wish to stop a default event in mootools I can do this:
$('form').addEvent('submit', function(e) {
e.stop();
//Do stuff here
});
However, I don’t like using an anonymous function in events because I often want to reuse the code. Lets say I have a validate function. I could do this:
$('form').addEvent('submit', validate);
which works fine until I want to stop the default event. validate obviously doesn’t know what e is so I can’t just do e.stop(). Also I’ve tried passing the event as a variable to validate but whenever I use a named function with parameters, the function gets called automatically on domready, rather than on the event firing. Even worse, an error is thrown when the event is fired.
What am I doing wrong?
UPDATE: Here is the validate function in full, just in case. However, since the error is occurring after the first line, I doubt anything after is being called so it is probably irrelevant.
var validate = function(e) {
e.stop();
if(this.get('tag') === 'form') {
this.getElements('input.text').each(validate);
}
else {
element = this;
div = element.getParent();
input = element.get('value');
filter = JSON.decode(div.get('filter'));
if(!filter.some(function(value, key) {
if(value === 'required') if(!setAndNotEmpty(element, input)) return true;
if(value === 'email') if(!isEmail(element, input)) return true;
if(value === 'date') if(!isDate(element, input)) return true;
if(value === 'time') if(!isTime(element, input)) return true;
if(key === 'chars') if(!charsLessThan(element, input, value)) return true;
if(key === 'words') if(!wordsLessThan(element, input, value)) return true;
return false;
})) setFault('', element);
}
}
you need to declare “validate” as follows:
Then you can use e.stop()
of note is that in jQuery, you can also return a result from a method to stop propogation. I’m not sure if mootools allows this, but you could possibly do this by:
To answer the “what am I doing wrong” part – you’re simply misunderstanding what is happening when you pass in an anonymous method. Passing an anonymous method
function(e) {}is not causingeto be passed, it is simply defining the name of the first argument to be passed in. The event object will be passed into the method whether or not the method names the argument, hence you will find that the following would also work: