【问题标题】:JS object method call not working from callbackJS对象方法调用不能从回调中工作
【发布时间】:2014-02-25 09:15:55
【问题描述】:

我对原型 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 将知道构造函数变量。

我不想使用这个额外的功能,如果您对此问题有任何解决方案,请告诉我!

非常感谢各位! :)

解决方案:

成功:self.showResponse.bind(self)

【问题讨论】:

  • var hl = new HeaderLogin();
  • 试试success: self.showResponse.bind(self)
  • 哇哈哈,你就是男人!它的工作,谢谢! :)

标签: javascript object callback prototype ajaxform


【解决方案1】:

很久没做这个了,你可以试试

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

【讨论】:

  • 不,我已经尝试过了:var self = this, self___ = self;self___.showResponse 但我遇到了同样的问题。 :)
猜你喜欢
  • 2011-10-22
  • 2019-03-25
  • 1970-01-01
  • 1970-01-01
  • 2021-09-25
  • 2014-03-30
  • 2017-05-02
  • 2019-12-20
  • 1970-01-01
相关资源
最近更新 更多