在 jquery.ajax 回调中获取类实例
我试图让 jQuery.ajax 回调调用实例来处理消息。但是,我无法将调用实例放入函数中。
在 GetHistory 调用中,返回消息列表,我希望 Process 方法对每一条消息进行操作。问题是在回调函数执行期间返回错误,指出“this.Process 未定义”。这就是为什么我猜测实例没有被设置。
我还尝试将参数添加到“context:this”的 .ajax 中,但这似乎没有帮助。
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'
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'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否尝试过使用 => (粗箭头)如Coffeescript/Javascript 变量范围?
Have you tried using => (the fat arrow) as suggested in Coffeescript/Javascript variable scope?
我很惊讶
context: this
不起作用。您应该能够使用它,或者按照 Paul 建议使用=>
(最简洁),或者使用经典的self = this
(更有效):请注意我假设您使用语法
obj.GetHistory()
调用GetHistory
,其中obj
是您想要的对象this
指向成功
回调。您可能需要使用=>
而不是->
来定义GetHistory
,这样,即使您将其与类实例分离,上下文仍然是相同的。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 classicself = this
(more efficient):Note that I'm assuming that you're calling
GetHistory
with the syntaxobj.GetHistory()
, whereobj
is the object that you wantthis
to point to in thesuccess
callback. You might want to defineGetHistory
with=>
instead of->
so that, even if you detach it from the class instance, the context will still be the same.