Search code examples
mvpractivejs

How can I add Ractive instances to a list? in a parent Ractive instance?


I already have a Ractive instance (or component - it could be either) and I want to add it to a list in another Ractive instance. Something like this:

var ListItemOne = new Ractive({
  data: { key: "hello" }
});

var ListItemTwo = new Ractive({
  data: { key: "world" }
});

var ractive = new Ractive({
  el: "#output",
  template: "#template",
  data: { greeting: 'hi', name: 'there',
      listItems: [
        ListItemOne,
        ListItemTwo
      ]
    }
});

Template:

<p>{{greeting}} {{name}}!</p>

<ul>
  {{#listItems}}
  <li>{{key}}</li>
  {{/listItems}}
</ul>

jsbin

Or using a method:

var ractive = new Ractive({
  el: "#output",
  template: "#template",
  data: {
    greeting: 'hi', name: 'there',
    listItems: []
   },

  addListItem: function(listItem){
    this.get('listItems').push(listItem);
  }
});

ractive.addListItem(ListItemOne);
ractive.addListItem(ListItemTwo);

jsbin

Is it possible to use Ractive in this way?


Please note that I do not want this:

var ractive = new Ractive({
  el: "#output",
  template: "#template",
  data: { greeting: 'hi', name: 'there',
      listItems: [
        { key: "hello" },
        { key: "world" }
      ]
    }
});

As I already have the Ractive instances/components, and I am using MVP to define explicitly define the interface between application and view.


Solution

  • The items in the list are ractive instances, so you have to call the get method to access their data if you want to use them that way (see http://jsbin.com/nomutofati/1/edit?html,js,output):

    <ul>
      {{#listItems}}
      <li>{{this.get('key')}}</li>
      {{/listItems}}
    </ul>