嵌套的Backbone Model不提取数据

时间:2013-11-27 18:36:21

标签: javascript ruby-on-rails backbone.js

我有一个Backbone / Rails应用程序,它列出了服务器并显示了已部署到特定服务器的应用程序。它由Rails API支持。我在rails erb文件中填充引导数据中的服务器,但是当我尝试加载特定服务器的已部署应用程序时,从不调用服务器(由日志消息确认)。如果我只是访问网址,我可以恢复部署的应用程序,所以我很确定我的Backbone应用程序出了问题。

这是我的应用程序启动:

window.WhatsDeployed =
Models: {}
Collections: {}
Views: {}
Routers: {}
initialize: (initialModels) -> 
    @start(initialModels)

start: (initialModels) ->
    @collection = new WhatsDeployed.Collections.Servers()
    @view = new WhatsDeployed.Views.ServersIndex({collection: @collection })
    @collection.reset(initialModels)

我的观点

class WhatsDeployed.Views.ServersIndex extends Backbone.View
el:"#serverDetails"

template: JST['servers/index']

initialize: ->
    @collection.bind("reset", this.render, this)

render: ->
    @selected = _.first(@collection.models)
    $(@el).html @template({collection: @collection, selected: @selected})
    this

我的服务器型号

class WhatsDeployed.Models.Server extends Backbone.Model
deployed_apps: ->
    @_deployed_apps = new WhatsDeployed.Collections.DeployedApps({server: @})
    @_deployed_apps.fetch() 
    console.log(@_deployed_apps)
    @_deployed_apps

My DeployedApps Collection

class WhatsDeployed.Collections.DeployedApps extends Backbone.Collection
url: -> 
    '/servers/#{@server.id}/deployed_apps.json' 

model: WhatsDeployed.Models.DeployedApp

initialize: (options) ->
    @server = options.server

最后是我的生态模板

<h1>Servers</h1>
  <p>
    <select id="servers">
      <% for server in @collection.models: %>
        <option id="<%= server.id %>"><%= server.attributes["name"] %></option>
      <% end %>
    </select>
  </p>

  <table>
    <tr>
      <th>Deployed Apps</th>
    </tr>
    <% for app in @selected.deployed_apps(): %>
       <tr>
          <td>Hi <%= app %></td>
       </tr>
    <% end %>
   </table>

ServerModel中的fetch调用不会失败并且似乎有效,但API从未被调用,并且该集合的数据似乎不正确。

我是Backbone的新手,所以我一直在努力解决这个问题,但是我可能很容易(我希望)我很想念。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:4)

您必须添加成功回调以使用@_deployed_apps的获取结果,如下所示:

class WhatsDeployed.Models.Server extends Backbone.Model
    deployed_apps: ->
        @_deployed_apps = new WhatsDeployed.Collections.DeployedApps({server: @})
        @_deployed_apps.fetch().success ()=>
            console.log(@_deployed_apps)