我显示了待处理邀请的列表。当用户接受邀请时,我想隐藏该邀请并显示下一个邀请(如果有)。
使用此 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/