Thursday, October 14, 2010

Mootools Function.Bind

There are alot of cases when you need to pass some value to the function you have hooked on an event. For example, consider there is an image. you want to hook an event on the image that when the mouse is moved on the image, a value is passed to the function by which the opacity of the image should be increased. Consider the following code for this;

var opacVal = 0.9;
$('someImage').addEvent('mousemove', 
                        function(element, opacVal){
                            element.set({'opacity': opacVal});
                        }.bind( this, [$('someImage'), opacVal])
                       );

However, there is a problem with above approach. Since, we have forcefully bound the parameters of the function, therefore, the event object is not passed to the function. If you want to pass the event object aswell, then use the bindWithEvent function of mootools. Consider the following code;


var opacVal = 0.9;
$('someImage').addEvent('mousemove', 
                       function(element, opacVal){
                          element.set({'opacity': opacVal});
                          event.stop();
                       }.bindWithEvent( this, [$('someImage'), opacVal])
                       );

No comments:

Post a Comment