javascript - Coffeescript ajax 成功调用外部函数

标签 javascript jquery ajax coffeescript

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

使用此 Coffeescript 代码,showNextInvitation() 会抛出“未捕获的类型错误:未定义不是函数”:

$('#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

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

最佳答案

您需要保留粗箭头以确保成功:并存储_this

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

代码片段中包含 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()

第二个片段期望 #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

关于javascript - Coffeescript ajax 成功调用外部函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23835624/

相关文章:

javascript - 在 C# 中使用 `x += 1` 而不是 `++x` 是否有任何副作用?

javascript - Jquery Cycle Slider - 快速点击打破 slider

javascript - 如何创建由窗口滚动控制的颜色过渡

javascript - 使用 AJAX 通过 Ruby on Rails 验证优惠券后获取数据

javascript - 如何强制ajax使用浏览器缓存不加载更新的json文件

javascript - jqGrid - 多次添加导航栏中的自定义按钮

javascript - 处理隐藏元素

javascript - 在 jquery 弹出窗口中禁用背景

php - ajax php从foreach循环更新进度条值

javascript - 在 then() block 中使用返回 promise 的函数