0

I am trying to get a jQuery.ajax to call back to the calling instance to process messages. However, I cannot get the calling instance into the function.

In the GetHistory call, a list of messages are returned and I want the Process method to act on each one. The problem is that during the callback function execution an error is returned stating "this.Process is undefined". This is why I am guessing the instance is not being set.

I also tried adding the parameter to .ajax of 'context:this', but that didn't seem to help.

class MessageHandler

  @messages: []

  Process: (message) ->
      messages.push message

  GetHistory: ->    
    jQuery.ajax url:'/home/BidDetail', dataType: 'json', data: 'auctionId=1', success:     (data) ->
      @Process record for record in data.records when record.type == 'BID'

2 Answers 2

4

Have you tried using => (the fat arrow) as suggested in Coffeescript/Javascript variable scope?

Sign up to request clarification or add additional context in comments.

Comments

0

I'm surprised that context: this doesn't work. You should be able to either use that, or use => as Paul suggests (most succinct), or use the classic self = this (more efficient):

GetHistory: ->    
  self = this
  jQuery.ajax url:'/home/BidDetail', dataType: 'json', data: 'auctionId=1', success: (data) ->
    self.Process record for record in data.records when record.type == 'BID'

Note that I'm assuming that you're calling GetHistory with the syntax obj.GetHistory(), where obj is the object that you want this to point to in the success callback. You might want to define GetHistory with => instead of -> so that, even if you detach it from the class instance, the context will still be the same.

2 Comments

thanks - I was thinking that 'this' being in the context of the ajax callback would be different.
@S. Hebert Er, it is. Sorry, I've corrected the code in my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.