-->

How to display Backbone nested attribute using Eco

2019-08-03 04:55发布

问题:

I've followed Ryan Bates' example on Backbone.js to start a project using Backbone + Eco. It's great. However, I'm stuck trying to display a nested attribute. For example, I'm trying to do this: <%= @stream.user.get('name') %> in index.jst.eco and I'm getting Uncaught TypeError: Cannot call method 'get' of undefined However, I can get <%= @stream.get('stream_type') %> to work.

Here's the REST API data:

[
:   {
:   :   "id":"5004095283de4ca9ff000005",
:   :   "created_at":"2012-07-16T12:30:10Z",
:   :   "stream_type":"project",
:   :   "user":
:   :   {
:   :   :   "id":"5002f30560de7d0ffb000003",
:   :   :   "name":"Regular User2"
:   :   },
...

I've also tried extending my Model using Backbone.DeepModel but that didn't seem to work.

class Project1.Collections.Streams extends Backbone.Collection
  url: '/streams'
  model: Topaz.Models.Stream

class Project1.Models.Stream extends Backbone.DeepModel

Here's my views on the collection, pretty standard.

class Project1.Views.StreamsIndex extends Backbone.View
  #views/streams/index.js
  template: JST['streams/index']

  initialize: ->
    @collection.on('reset', @render, this)
    @collection.on('add', @appendStream, this)  #rerenders entire template

  render: ->
    $(@el).html(@template())
    @collection.each(@appendStream)
    this

  appendStream: (stream) =>
    view = new Topaz.Views.Stream(model: stream)
    @$('#streams').append(view.render().el) # looks for the #entries element within the view’s element and not on the page directly

and here's the View for the model

class Project1.Views.Stream extends Backbone.View

  template: JST['streams/show']
  className: 'stream-item'

  initialize: ->
    @model.on('change', @render, this)   #The change event is triggered by Backbone when a model saves

  render: ->
    $(@el).html(@template(stream: @model))
    this