Getting class instance back on jquery.ajax callback
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 t开发者_JS百科o 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'
Have you tried using => (the fat arrow) as suggested in Coffeescript/Javascript variable scope?
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.
精彩评论