2011-07-11 2 views
0

は次のとおりであるにバインドされたCSSクラスの結果から、クラスの関数を呼び出す:イベントが結合しないMooToolsは - MooToolsは1.3.2</p> <p>コードを使用して「いない関数」エラー

var DNReportAbuse = new Class({ 

Extends: DNUserDialog, 
comment_id: null, 
container: null, 

initialize: function(classname) 
{ 
    var bindclass = $(document.body).getElements(classname); 

    bindclass.each(function(el) { 
     el.addEvents({ 
      click: function() { 
       this.reportComment(); 
      }.bind(this) 
     }); 
    }); 
}, 

reportComment: function() { 
    this.preventDefault(); 
    alert('hello'); 
    return false; 
} 
}); 

、そして時に " this.reportComment(); "が "alert( 'hello world');に置き換えられました。

... "this.reportComment()"を使用すると、代わりにFirebugが "関数this.reportComment()は関数ではありません"と説明したエラーが表示されます。

私の問題には、適切な範囲外のクラス関数を参照することと関係があると思いますが、私はちょっと困っています...または問題を解決する方法が少しあります。最終目標は、reportComment()関数をCSSクラスのすべてのメンバー(ページあたり20個まで)にオンクリックでバインドすることです。難しいのは、reportComment()関数を "this.reportComment()"で参照すると、関数が存在しないと明示的にエラーが発生します。

Stack Overflowに関するよくある質問を見ると、この問題には答えられないようです...誰かが私に正しい方向を向けることを望むように頼んでいます。

答えて

0

あなたがbindeventsといくつかの問題を抱えて:

initialize: function(classname) 
{ 
    var bindclass = $(document.body).getElements(classname); 
    var _self = this; //var to store the 'real' this you will use 
    bindclass.each(function(el) { 
     el.addEvents({ 
      click: function(event) { //pass the event 
       this.reportComment(event); 
      }.bind(_self) //'this' is referring to the inner each function callback 
     }); 
    }); 
}, 

reportComment: function(event) { 
    event.preventDefault(); //preventDefault on the event, not on 'this' 
    alert('hello'); 
    return false; 
} 
+0

ありがとうございました - それは私がまさに必要です。私はイベントと要素がどこかで混ざっているのを知っていました... – user839318

+0

あなたは 'bindclass.each(fn(el){el.addEvents {{click:this.reportComment.bind(this)});} this) 'この場合、スコープを' each loop'に入れておくと、anonラッパーは必要ありません:) –