Richard the Lionheart
Richard the Lionheart

Reputation: 350

Coffescript, Backbone - jQuery.ajax done callback function scope

I'm using AJAX to send a collection stringified to JSON. It gets decoded, validated and saved to session.

It works in Firefox - $_SESSION['key'] is available, it doesn't work in Chrome.

I think there is a problem with AJAX done firing too soon when I use window.location.href = 'checkout'. I wanted to fix it but I can't log from inside done callback or from ajaxdone method.

I don't understand why adding '=>' doesn't help. It caches the whole object to _this, doesn't it?

send: (data) ->
  console.log this
  jQuery
    .ajax({
      type: "POST",
      url: 'checkout',
      data: {order: data},
      dataType: 'json',
      done: (data) => 
        this.ajaxdone()
    })
  this

ajaxdone: ->
  #window.location.href = 'checkout'
  console.log this

Upvotes: 0

Views: 228

Answers (1)

mu is too short
mu is too short

Reputation: 434755

There is no done option to $.ajax. There is a complete option which is

called when the request finishes (after success and error callbacks are executed).

so maybe you mean:

jQuery.ajax(
  #...
  complete: => @ajaxdone()
)

instead. There is a done method on jqXHR so you could say:

jQuery.ajax(
  #...
).done => @ajaxdone()

but done is "An alternative construct to the success callback option" so it won't be called if there was an error. If you want ajaxdone to always get called then use always (which acts like the complete option):

jQuery.ajax(
  #...
).always => @ajaxdone()

Upvotes: 1

Related Questions