在 jquery.ajax 回调中获取类实例

发布于 2024-11-29 14:48:27 字数 542 浏览 0 评论 0原文

我试图让 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ˇ宁静的妩媚 2024-12-06 14:48:27

您是否尝试过使用 => (粗箭头)如Coffeescript/Javascript 变量范围

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

于我来说 2024-12-06 14:48:27

我很惊讶 context: this 不起作用。您应该能够使用它,或者按照 Paul 建议使用 => (最简洁),或者使用经典的 self = this (更有效):

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'

请注意我假设您使用语法 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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文