2009-10-16 4 views
0

J'ai une question sur l'appel d'autres fonctions dans une classe mootools. Par exemple:Appelez les méthodes de la classe mootools

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 test2 and pass the input element? 
     }) 
    }); 
    }, 
    test2: function(e){ 
    alert(e); 
    }  
}); 

Merci.

Répondre

1
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); 
     } 
}); 
1

Il serait préférable d'utiliser bind à la place, si vous le pouvez. Je voudrais Refactor comme si (si vous n'avez pas besoin de passer l'élément déclencheur lui-même, sinon, vous pouvez l'obtenir à partir de la propriété event.target)

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); 
    } 
}); 

vérifier ici: http://mooshell.net/rWUzN/

0

Vous devez utiliser bindWithEvent pour obtenir à la fois l'événement et ceci dans votre fonction, aussi vous n'avez pas besoin d'appeler chaque cause mootools le fera pour vous:

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); 
    } 
}); 
Questions connexes