Attaching and detaching events

23 views
Skip to first unread message

Roo

unread,
Jul 24, 2014, 7:54:58 AM7/24/14
to mootool...@googlegroups.com
Hi all,

Bit of a newbie question this.

I usally add my events to elements like this using an anonymous function I think its called.

$$('.myClass').addEvent( 'blur', function(e){
console.log(e.target.id); <--- I have the event available here
}

I now have a need to attach and detach an event dynamically so I want to declare the function like so;

var myFunction(event){

}

then attach like;

$$('.myClass').addEvent( 'blur', myFunction(event))

But I dont know how to ensure that the element and event get bound to the function.

Thanks
Rolf

Sérgio Crisóstomo

unread,
Jul 24, 2014, 8:11:48 AM7/24/14
to mootool...@googlegroups.com
Rolf, check this fiddle: http://jsfiddle.net/4E4P4/

So you could do var myFn = function(event){ // etc

and then 

el.addEvent('type', myFn); // same for removeEvent

When you use the parenthesis inside the addEvent function parameters like `el.addEvent( 'blur', myFunction(event))` you are actually calling/running your function instead of just referring/pointing to it. So use just "myFunction".

Roo

unread,
Jul 25, 2014, 4:52:12 AM7/25/14
to mootool...@googlegroups.com
wow that easy! I am really going to have to sit down and get some basic OO knowledge...just always so busy just getting stuff done!

Thanks
Rolf

Gonzalo Rubio

unread,
Jul 25, 2014, 10:07:29 AM7/25/14
to mootool...@googlegroups.com
Actually that's more of a thing of functional programming, where functions are first-class citizens.

It's the magic of being a multi paradigm programming language, you can mix and match styles to better fit your preferred way of doing things.

Reply all
Reply to author
Forward
0 new messages