2014-02-25 30 views
0

我有一個小的問題與原型JS編碼,並與回調。它看起來不能正常工作。JS對象方法調用不從回調工作

這裏是我的示例:

var hl = new HeaderLogin; 
hl.drawPanel(); 

var HeaderLogin = function(elem) { 
    this.init = true; 
    this.jsvh = JSViewHandler.getInstance(); 
}; 


HeaderLogin.prototype.drawPanel = function() { 
    var self = this; 
    ... 
    this.jsvh.get({ 
     ... 
     'callback': function(rsp, templates) { 
      ... 
      $('#jsview_user_login_form').ajaxForm({success: asd}); 
     } 
    }); 
    function asd(rspJSON, statusText, xhr, $form) { 
     self.showResponse(rspJSON, statusText, xhr, $form); 
    } 
}; 

HeaderLogin.prototype.showResponse = function(rspJSON, statusText, xhr, $form) { 
    if (typeof this.init === 'undefined') { 
     alert('not an object'); 
    } 
    ... 
} 

我有打電話給showResponse函數形式發出後,但如果我用{success: self.showResponse}init將不存在。它看起來像一個靜態調用,我不能從構造函數訪問任何變量。如果我創建了本地asd函數,並且我將其用作成功回調函數,那麼showRespons將知道構造函數變量。

我不想使用這個額外的功能,如果您有任何關於這個問題的解決方案,請讓我知道!

非常感謝你們! :)

SOLUTION:

成功:self.showResponse.bind(個體經營)

+0

var hl = new HeaderLogin(); – Triode

+1

嘗試'成功:self.showResponse.bind(self)' – elclanrs

+0

Vahahaha,你是男人!它的工作,謝謝! :) –

回答

0

我沒有在很長一段時間這樣做,但你可以嘗試用

'callback': function(rsp, templates) { 
    ... 
    var s = self; 
    $('#jsview_user_login_form').ajaxForm({success: s.showResponse}); 
} 
+0

不,我已經嘗試過了:var self = this,self___ = self;''self ___。showResponse'但我遇到了同樣的問題。 :) –