just__matt
just__matt

Reputation: 484

Spine JS error rendering .eco template using Hem : "Cannot read property 'length' of undefined"

Learning spine.js I completed both the tutorials no problem, seems like a great framework, but this simple little problem is driving me nuts, because I have no idea what I can do to fix it...

From what I understand the variable @list should be accessible by the .eco template (compiled by hem), but it's not, has anybody else encountered this?

Can someone please show me where I am going wrong?

Users.coffee

Spine = require('spine')
User  = require('models/user')
$     = Spine.$

class Show extends Spine.Controller
  className: 'UserApp'

  events:
    'click .NewUser' : 'new'

  constructor: ->
    super    
    User.bind('create refresh change', @render)
    @active @render

  render: =>
    #get all users and render list
    @list= [1,2,3,4,5]
    console.log(@list)
    @html require('views/UserApp')(@list)

  new: ->
    @navigate('/users','create')

UserApp.eco

 <% if @list.length: %>
     <% for i in @list: %>
      <%= i %>
     <% end %>
    <% else: %>
     Why you no work!?
    <% end %>

Upvotes: 1

Views: 944

Answers (2)

lucapette
lucapette

Reputation: 20724

@html require('views/UserApp')()

expects an hash object as parameter. So, if you want to use a @list variable in your view (ala Rails I mean) you have to do something like the following:

@html require('views/UserApp')(list: @list)

where the key will be the name of your variable in the view. So using:

@html require('views/UserApp')(@list)

like you're doing will bring to the view the @list variable as the current @ or this and in your view you should be able to use it in the following way:

<% if @.length: %>
     <% for i in @: %>
      <%= i %>
     <% end %>
<% else: %>
     Why you no work!?
<% end %>

But it's not that readable.

Upvotes: 4

Kevin Ennis
Kevin Ennis

Reputation: 14466

I think the template expects to receive an object. Then you access a property of that object by using @key_name;

Try something like this ( Disclaimer: I don't know Coffeescript )

render: =>
    #get all users and render list
    @item = {}
    @item.list = [1,2,3,4,5]
    @html require('views/UserApp')(@item)

Upvotes: 3

Related Questions