在 Coffeescript 中重用 ajax 变量

Reuse ajax variable in Coffeescript

当我尝试通过 WebApi 插入值时,我的 backbone 应用程序的一部分需要用户确认。

我有这个代码:

@xhr = $.post '/api/entity/create', @data

@xhr.done (resp) =>
    if @xhr.status == 202
        # Some code for confirmation box
         @data.Force = true
         @xhr = $.post '/api/entity/create', @data # Problem is here

@xhr.fail (resp) =>
    # Code for error

当我强制插入时,我在 WebApi 调用后没有通过@xhr.done

你知道为什么它不起作用吗?

谢谢

那是因为这是一个新的 @xhr,并且回调附加到旧的。您可以将它移动到另一个方法并重新使用它(我想您在代码周围有一个 class):

post: ->

  @xhr = $.post '/api/entity/create', @data

  @xhr.done (resp) =>
    if @xhr.status == 202
      # Some code for confirmation box
      @data.Force = true
      @post()

  @xhr.fail (resp) =>
    # Code for error