views:

156

answers:

3

Dear friends

I have a question about calling other functions in a mootools class. For example:

var f = new Class('foo',
{
    test1: function(){
     var table = new Element(........);
     ....
     ...

      $(table).getElements('input').each(function(input) {
                 input.addEvent('change', function() {
       **// how could I call the test2 and pass the input element ?**
                 }); 
            });

     },


    test2: function(e){
      alert(e);
     }


});

Thank you.

+1  A: 
var f = new Class('foo',
{
    test1: function(){
        var table = new Element(........);
        var me = this;
         $(table).getElements('input').each(function(input) {
                    input.addEvent('change', function() {
                        me.test2("foo");
                    }); 
            });
        },
    test2: function(e){
                alert(e);
        }
});
Dark Falcon
+1  A: 

it would be better to use bind instead, if you can. i'd refactor it like so (if you don't need to pass the trigger element itself, else, you can get it from the event.target property)

var f = new Class('foo', {
    test1: function() {
        var table = new Element(........);

        // no need to use $(), table is already an object.
        table.getElements('input').addEvents({
            change: function(e) {
                this.test2(e);
            }.bind(this)          // bind the function to the scope of the class and 
                                  // not the element trigger
        });
    },
    test2: function(e){
        var e = new Event(e);
        console.log(e.target);
    }
});

check it here: http://mooshell.net/rWUzN/

Dimitar Christoff
A: 

You have to use bindWithEvent to get both the event and this in your function, also you dont need to call each cause mootools will do this for you:

var f = new Class('foo',
    {
        test1: function(){
            var table = new Element(........);
            table.getElements('input').addEvent('change', this.test2.bindWithEvent(this)); 
     },
        test2: function(e){
                    alert(e);
     }
 });
eskimoblood