Search code examples
ractivejs

fails to compute attribute derived from components collection


ref: this jsfiddle

I have the following (Coffeescript) code:

Member = Ractive.extend
  template : "<p>{{name}} {{age}}</p>"
  computed :
    age : ->
      parseInt(@get('age_in_days')/365)

new Ractive
  el : "#family"
  template : "{{#members}}<member name='{{name}}' age_in_days='{{age_in_days}}'/>{{/members}}{{youngest}}"
  components :
    member : Member
  data:
    members : [
      {name : 'Fred', age_in_days: 8000},
      {name : 'Barney', age_in_days: 10000},
      {name : 'Wilma', age_in_days: 7000}
      ]
  computed :
    all_ages : ->
      _(@findAllComponents('member')).map (member)->
        member.get('age')
    youngest : ->
      _(@get('all_ages')).min()

The problem is in the computed attributes of the root Ractive instance. An error is thrown ("TypeError: Cannot read property 'findAllComponents' of undefined") from deep within the Ractive code. And the computed attributes "all_ages" and "youngest" are not computed or rendered.

Any insight would be greatly appreciated. Thanks in advance.


Solution

  • It seems to work in oninit, but not in a computed context.

    oninit: ->
        console.log( (@.findAllComponents('member') ) )
    

    Guess some context is lost somewhere. Maybe check with them on github?

    A workaround would be -

    computed :
        all_ages : ->
           @get('members').map((m) -> m.age_in_days)  
    
        youngest : ->
          ages =  @get('all_ages')
          Math.min.apply @, ages