2010-09-15 81 views
1

由于在发送element.addEvent中的方法时我无法使用“this”,因此在实现mootools中的类时出现问题。如何在mootools类中的函数中调用此函数

说我有这样的mootools类:

var Dude = new Class({ 

    highlightColor: '#f00', 

    doStuff: function() { 
     var parent = $('theParentId'); 

     new Element('div', {'html': 'Click me'}) 
      .inject(parent) 
      .addEvent('click', function(){ 

       new Element('div', {'html': 'you clicked'}) 
        .highlight(this.highlightColor); 

      }); 
    }, 

}); 

此代码将抛出的addEvent方法调用内部异常,因为this突然在另一种情况下。有没有其他方法来获取对象的highlightColor(或mootools类可能有的其他成员)?

回答

2

的“MooTools的方式”将使用bindWithEvent功能:

var Dude = new Class({ 

    highlightColor: '#f00', 

    doStuff: function() { 
     var parent = $('theParentId'); 

     new Element('div', {'html': 'Click me'}) 
      .inject(parent) 
      .addEvent('click', function(event){ 

       new Element('div', {'html': 'you clicked'}) 
        .highlight(this.highlightColor); // <- `this` refers to the 
      }.bindWithEvent(this));     // outer `this` value 
    }, 
    //... 
}); 

这种方法可以让您保存在一个函数this值,并在必要时通过额外的参数。

绑定函数的第一个参数将引用触发事件的Event对象。

+1

应该使用'bind'来代替'bindWithEvent' - 这是核心开发者鼓励不要使用'bindWithEvent'的“mootools方式”。 – 2010-09-15 20:40:14

+2

@Oskar,好吧,'bindWithEvent'已经被完全做成了,[documentation](http://j.mp/cAoTn4)在使用addEvent时特别推荐它的用法:“这允许函数与Element一起使用:addEvent和arguments。“,尽管我承认使用bind的好处之一是,ECMAScript 5标准的本地实现Function.prototype.bind将很快在所有浏览器上提供,本机实现总是有很好的性能。无论如何,如果Core开发人员不鼓励使用此方法,那么文档中的注释将会有所帮助。 – CMS 2010-09-15 20:49:10

+0

我同意Oskar的意见,它使用'bind'更常见 - 保持范围到类实例的工作就像这样完成。就我的理解而言,在这里你不需要'bindWithEvent' - 他在回调中访问的所有内容都是'this.highlightColor'属性,所以将范围保持到类实例就足够了。该事件根本不需要传递,因为回调已经按照定义直接访问它。例如'... click ...“,this.methodName.bind(this)'也会将事件对象传递给方法作为第一个参数,那么'bindWithEvent'有什么好的测试用例吗? – 2010-09-16 00:18:53

3

你需要每次使用的功能(上addEventseach)时间

var Dude = new Class({ 

    highlightColor: '#f00', 

    doStuff: function() { 
     var parent = $('theParentId'); 

     new Element('div', {'html': 'Click me'}) 
      .inject(parent) 
      .addEvent('click', function(){ 

       new Element('div', {'html': 'you clicked'}) 
        .highlight(this.highlightColor); 

      }.bind(this)); 
    } 
}); 

是carefoul与功能doStuff最后昏迷参考功能绑定... Firefox是像一个母亲会foregive你,但IEXPLORER是BMF将抛出一个错误,并不会告诉你为什么

2

@CMS是在一个正确的轨道,但bindWithEvent现在已经过时和documentation建议使用此代码来代替:

myElement.addEvent('click', function(e){ 
    myFunction.call(bind, e); 
}); 


如果你想将事件绑定元素传递给你的类方法,你可以做这样的:

var self = this; // 'this' is class reference 
elements.addEvent('click', function(e){ 
    self.myClassMethod(this, e); // now 'this' is clicked element 
}); 

现在你得到了正确的元素传递给你的方法,并准备操纵上。