2013-04-24 61 views
0

我有一個函數用於附加處理程序到事件,它的工作時傳遞一個匿名函數,但當我聲明函數作爲一個領域的對象,它不工作和處理程序是未定義未定義jQuery處理程序(handler.guid)

validationObj = (function(API){ 

    this.validate = function (id2, idN2){ 
     //code 


     //doesn't work 
     //this way i get an handler.guid error on functionFromMyApi 
     API.attach_events({"keyup": run_func(id1, id2) },"id"); 


     // work's ok 
     API.attach_events({"keyup": function(){ 
             // same code here from run_func 
            } 
          },"id"); 

      //code 
    }; 


    var run_func = function (id1, id2){ 

     var obj1 = document.getElementById(id1); 
     var obj2= document.getElementById(id2); 

     var show_err = false; 


     API.functionFromMyApi(); 



     //code 
     // more code 

    }; 


})(api); 

使用jQuery 1.2.6

回答

1

當你這樣做:

API.attach_events({"keyup": run_func(id1, id2) },"id"); 

你不能傳遞一個函數引用,就像你使用匿名函數時一樣,你調用run_func並傳遞它的返回值。如果run_func沒有參數,那麼你可以做:

API.attach_events({"keyup": run_func},"id"); 

然而,由於這樣做,你還是會需要使用匿名函數:

API.attach_events({"keyup": function() {run_func(id1, id2)} },"id"); 
+0

是什麼奇怪的是,我進入調試器在run_func中,它運行正常,當我回到API.attach_events({「keyup」:run_func(id1,id2)},「id」);我得到錯誤。 我希望在輸入run_func時得到錯誤。 – 2013-04-24 09:20:23

+0

我運行它沒有參數只是爲了看到結果,它工作正常 – 2013-04-24 09:53:57