代码之家  ›  专栏  ›  技术社区  ›  Mironline Naeem Bashir

调用mootools类中的方法

  •  0
  • Mironline Naeem Bashir  · 技术社区  · 15 年前

    我有一个关于在一个 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);
      }    
    });
    

    非常感谢。

    3 回复  |  直到 9 年前
        1
  •  1
  •   Dark Falcon    15 年前
    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);
            }
    });
    
        2
  •  1
  •   Dimitar Christoff    15 年前

    如果可以的话,最好使用bind。我会像这样重构它(如果不需要传递触发器元素本身,那么可以从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);
        }
    });
    

    请在此处查看: http://mooshell.net/rWUzN/

        3
  •  0
  •   Andreas Köberle    15 年前

    您必须使用bindWithEvent在函数中同时获取事件和它,而且您不需要调用每个函数,因为mootools将为您执行以下操作:

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