如何“获取” $.ajax() 变量与类中的coffescript? (导轨 3.1)

发布于 2024-12-16 17:51:16 字数 807 浏览 1 评论 0原文

这是我在这里的第一个问题,尽管我是这里的常客。我试图自己寻找答案,但没有快乐。

所以,我在 coffescript (Rails 3.1) 中有一个类,如下所示:

root = global ? window

class root.CTimelineGraph
  constructor: (div, @w, @nw, @table_name) ->
    @columnNames = ""
    @dbReadTable(@table_name)
    ..

dbReadTable: (table_name) ->
    if table_name == "SOMETABLE" then @dbReadTableA1()

dbReadTableA1: ->
    sipa = ""
    $.ajax
      async: false
      type: "GET"
      url: "ajax/getcolumnnames"
      dataType: 'json'
      success: (data) ->
        sipa = data
    @columnNames = sipa

我的问题是,如何使用从 ajax 返回的数据填充 @columnNames (在构造函数中声明) /getcolumnnames 控制器?我使用第三个变量 sipa 从 success 函数中获取数据。我这样做错了吗?

我发布的代码正在运行。我问这个问题是因为我打算让这个类的许多实例都大量调用dbReadTable

谢谢。

This is my first question here, though I'm frequent visitor. I tried to find answers on my own to this but no joy.

So, I have a class in coffescript (Rails 3.1) like this:

root = global ? window

class root.CTimelineGraph
  constructor: (div, @w, @nw, @table_name) ->
    @columnNames = ""
    @dbReadTable(@table_name)
    ..

dbReadTable: (table_name) ->
    if table_name == "SOMETABLE" then @dbReadTableA1()

dbReadTableA1: ->
    sipa = ""
    $.ajax
      async: false
      type: "GET"
      url: "ajax/getcolumnnames"
      dataType: 'json'
      success: (data) ->
        sipa = data
    @columnNames = sipa

My question is, how can I populate @columnNames (declared in the constructor) with the data that I get back from ajax/getcolumnnames controller? I'm using third variable sipa to get data out of success function. Am I doing this wrong?

The code I posted is working. I'm asking the question because I intend to have many instances of this class all calling dbReadTable a lot.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

枕梦 2024-12-23 17:51:17

这是一个更好的方法,无需额外的变量:

dbReadTableA1: =>
  $.ajax
    async: false
    type: "GET"
    url: "ajax/getcolumnnames"
    dataType: 'json'
    success: (data) =>
      @columnNames = data

关键是双箭头,它将 this 绑定到 success 回调中的类实例,这使得 @columnNames 在函数内可用。这还假设 dbReadTableA1 被声明为类中的成员函数。

Here's a better way, without the extra variable:

dbReadTableA1: =>
  $.ajax
    async: false
    type: "GET"
    url: "ajax/getcolumnnames"
    dataType: 'json'
    success: (data) =>
      @columnNames = data

The key is the double arrow which binds this to your class instance in the success callback, which makes @columnNames available inside the function. This also assumes that dbReadTableA1 is declared as a member function in the class.

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