Swell Swell - 1 month ago 7
CoffeeScript Question

Reuse ajax variable in Coffeescript

I have a part of my backbone application that requires a user confirmation when I try to insert a value through my WebApi.

I have this code:

@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


When I force the insertion I don't go through @xhr.done after my WebApi call

Do you have any clue why it doesn't work?

Thanks

Answer

That's because that's a new @xhr, and the callbacks are attached to the old. You can move it to another method and reuse it (I imagine you have a class around the code):

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
Comments