【问题标题】:Coffeescript ajax success call to external functionCoffeescript ajax成功调用外部函数
【发布时间】:2014-05-24 02:35:23
【问题描述】:

我有一个正在显示的待处理邀请列表。当用户接受一个邀请时,我想隐藏该邀请并显示下一个邀请(如果有)。

使用此 Coffeescript 代码,showNextInvitation() 会抛出“Uncaught TypeError: undefined is not a function”:

$('#invitations').on 'click', '.accept-invite-btn', () ->
   $(this).parents('form').ajaxSubmit(
       success: =>
           $(this).parents('.invitation').fadeOut()  
           showNextInvitation() 
   )
   return false

使用此代码,该功能可以正常工作,但目标邀请不会消失:

_this = this
$('#invitations').on 'click', '.accept-invite-btn', () ->
   $(this).parents('form').ajaxSubmit(
       success: ->
           $(this).parents('.invitation').fadeOut()  
           _this.showNextInvitation() 
   )
   return false

这显然是一个函数绑定问题。

【问题讨论】:

    标签: javascript jquery ajax coffeescript


    【解决方案1】:

    您需要保留success: 的粗箭头以及存储_this

    _this = this
    $('#invitations').on 'click', '.accept-invite-btn', () ->
        $(this).parents('form').ajaxSubmit(
            success: =>
                $(this).parents('.invitation').fadeOut()
                _this.showNextInvitation()
        )
        return false
    

    使用您的 sn-ps 中包含的 2 个函数,涉及 3 个不同的 this 值:

    # 1) `this` is an object with a `showNextInvitation` method
    
    $('#invitations').on 'click', '.accept-invite-btn', () ->
        # 2) `this` is the `.accept-invite-btn` element that captured the event
    
        $(this).parents('form').ajaxSubmit(
            success: ->
                # 3) `this` is the object managing the Ajax request, likely a jqXHR
    
        )
    

    虽然你已经通过定义_this 保存了#1,它允许调用它的方法。

    _this = this
    
    # ...
    
        _this.showNextInvitation()
    

    第二个 sn-p 期望 #3 与 #2 相同,胖箭头会这样做。


    或者,您也可以将#2 保存到它自己的变量中,可能是$element,并在整个过程中使用细箭头:

    _this = this
    $('#invitations').on 'click', '.accept-invite-btn', () ->
        $element = $(this)
    
        $element.parents('form').ajaxSubmit(
            success: ->
                $element.parents('.invitation').fadeOut()
                _this.showNextInvitation()
        )
        return false
    

    【讨论】:

    • 非常感谢!这正是我所希望的深入答案——我现在明白“为什么”并且将来能够更好地编码。奇怪的是,您提出的第一个解决方案不起作用 - 我相信它应该,我必须在其他地方有一个错误。第二个工作正常,所以为了时间,我正在使用它。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 2012-07-27
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2015-07-12
    • 2013-02-14
    相关资源
    最近更新 更多