【问题标题】:Issues returning a Request result in Batman.js在 Batman.js 中返回请求结果的问题
【发布时间】:2014-07-19 04:11:48
【问题描述】:

我在从 Batman.Request 调用返回结果时遇到问题。我已经评论了我要退货的区域。我很确定我不能只在那里调用 return,但我似乎找不到任何可以为我指明正确方向的文档。

型号:

class Web.Inbox extends Batman.Model
  @resourceName: 'inbox'

  @persist Web.InboxStorage

  @encodeTimestamps()

  @classAccessor 'task_entries', ->
    request = new Batman.Request
      url: 'http://0.0.0.0:3000/inbox'
      autosend: false
      success: (response) ->
        results = new Batman.Set
        results.add(Web.TaskEntry.createMultipleFromJSON(response))
        console.log(results) # The value I want is here!
        return results # I assume the issue is here
    request.send()

控制器:

class Web.InboxController extends Web.ApplicationController
  routingKey: 'inbox'

  index: (params) ->
    task_entries =  Web.Inbox.get('task_entries')
    @set('task_entries', task_entries)
    console.log(task_entries) # not the same value as I attempt to return 
                              # in the request

来自模型的控制台日志(我想要的):

Set {_storage: Array[1], length: 1, _batman: _Batman, constructor: function, isCollectionEventEmitter: true…}
_batman: _Batman
_storage: Array[1]
0: Array[15]
0: TaskEntry
1: TaskEntry
2: TaskEntry
3: TaskEntry
4: TaskEntry
5: TaskEntry
6: TaskEntry
7: TaskEntry
8: TaskEntry
9: TaskEntry
10: TaskEntry
11: TaskEntry
12: TaskEntry
13: TaskEntry
14: TaskEntry 

来自控制器的控制台日志:

Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}

感谢任何帮助!

【问题讨论】:

    标签: javascript coffeescript batman.js


    【解决方案1】:

    不确定你是否在 IRC 中看到了 bradstewart 的回复,以防万一,又来了:

    Web.Inbox.get('task_entries')
    

    此访问器触发 AJAX 请求,但它是异步的。它不会返回您要查找的值,因为该值仍在从服务器加载。正如 Brad 指出的那样,访问器返回 Batman.Request 对象,而不是来自服务器的值。

    您可以做的是让访问器返回一个Batman.Set,然后还使用访问器触发一个Batman.Request,它将记录加载到该集合中。当集合更新时,您的视图也将更新。例如:

      @classAccessor 'task_entries', ->
          @_entries = new Batman.Set
           new Batman.Request
            url: "/inbox"
            method: "GET"
            success: (data) =>
              records = Web.TaskEntry.createMultipleFromJSON(data)
              @_entries.add(records...) # if you're on master branch, you could use `@_entries.addArray(records)`
          return @_entries 
    

    这将导致访问器返回一个 Set,起初它是空的,但 Set 将由 Batman.Request 填充,并且您的视图将被更新。

    (哎呀,从gist交叉发布)

    【讨论】:

    • 我错过了那个回复。感谢您在此处发布!
    猜你喜欢
    • 2022-09-24
    • 1970-01-01
    • 2012-02-28
    • 2018-10-25
    • 2015-03-05
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 2019-12-05
    相关资源
    最近更新 更多