0

Suppose this:

Model Foo:
    -> id
    -> name
    -> description
    -> children[]

Where children is a collection of Foos. Every Foo can have zero or more children, all having the same basic structure as their parent.

What would be the proper way to do the view/template for this in Backbone.js? I am building on top of a Rails app if that makes any difference.

mga
  • 1,960
  • 1
  • 23
  • 31
  • This looks like a tree structure. Why not just have a view per `Foo` and depending on how you want to show it have a view template for each. What exactly is the question? – PhD Sep 18 '12 at 04:34
  • yes... it is a tree... the thing is the `Foo` view would need to be recursive and I'm not sure how to implement that in Backbone – mga Sep 18 '12 at 15:24
  • What do you mean the view would be recursive? Every recursive function can be written in an iterative form, so I'm not sure what the problem is. Can you give an example? – PhD Sep 18 '12 at 18:11

1 Answers1

0

I ended up using something similar to what is described here: Run Template in Template (recursion) within underscore.js template engine but I am using CoffeeScript so it is slightly different:

The view:

# foo.js.coffee

class MyApp.Views.Foo extends Backbone.View

template: JST['foo']

inititalize: ->
    #init stuff

render: =>
    templateFn = @template
    $(@el).html(@template(model: @model, templateFn: templateFn))
    @

The @model will have children inside that share the structure of their parent.

The template:

# foo.jst.eco
<%# other output stuff here %>

<%# there is a 'components' attribute that contains the children %>
<% if @model.get('components') : %>
<%# recursive output of components %>
    <% for e in @model.get('components') : %>
        <% foo = new MyApp.Models.Foo() %>
        <% foo.set(e) %>
        <%# note the - instead of = below... in my case the JSON contains HTML entities %>
        <%- @templateFn(model: component, templateFn: @templateFn) %>
    <% end %>
<% end %>
Community
  • 1
  • 1
mga
  • 1,960
  • 1
  • 23
  • 31