在Batman.js中返回Request结果的问题

时间:2014-07-19 04:11:49

标签: javascript coffeescript batman.js

我遇到了从Batman.Request调用返回结果的问题。我已经评论了我打电话给回程的区域。我非常确定我可以在那里打电话回来,但我似乎无法找到任何能够指明我正确方向的文件。

型号:

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 

来自Controller的控制台日志:

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

感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

不确定你是否在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将填充该Set,您的视图将被更新。

(哎呀,从gist交叉发布)