andy250
andy250

Reputation: 20414

Aurelia: rendering objects fetched from server in repeater and bind them with parent

I am trying to fetch a list of objects (JSON) from the server, then render them in a repeater, and have a click handler on each of those items to be handled by the parent view model. So far I have:

/* list.html */
<template>
  <require from="./components/player.html"></require>
  <div>
    <player repeat.for="p of players" containerless player-data.bind="p" dosth.call="dosth(p)"></player>
  </div>
</template>

Then the player custom element:

/* player.html */
<template>
  ${playerData.name}
  <button click.delegate="dosth()">DO STH</button>
<template>

And the player model:

/* player.ts */
import {customElement, bindable} from 'aurelia-framework';

@customElement('player')
export class PlayerModel {
  @bindable playerData: any;
  @bindable dosth;

  bind(ctxt: any) {
    console.log(ctxt);
  }
}

When I receive data from server:

return this.http.fetch('players')
    .then(response => response.json())
    .then(players => {
      for (let p of players) {
        var model = new PlayerModel();
        model.playerData = p;
        this.players.push(model);
      }
  });

Where this.players is an array property in the list.ts view model.

I have 2 issues:

  1. My bind method on the PlayerModel is not triggered - why?
  2. I can't get the dosth function to work. I am getting 'dosth' is not a function error.

Can anyone point me in the right direction?

Upvotes: 0

Views: 405

Answers (1)

Fabio
Fabio

Reputation: 11990

You are loading an HTML-Only custom element. If you have a view-model (in your case player.ts), you must require the custom element without .html. Like this:

<require from="./components/player"></require> <!-- no .html here -->

In addition, containerless in html markup only works for html-only custom elements. In your case, you must declare containerless in your view-model. Like this:

import {customElement, bindable, containerless} from 'aurelia-framework';

@containerless
@customElement('player')
export class PlayerModel {
  @bindable playerData: any;
  @bindable dosth;

  bind(ctxt: any) {
    console.log(ctxt);
  }
}

More information at http://aurelia.io/hub.html#/doc/article/aurelia/templating/latest/templating-custom-elements/2

Upvotes: 2

Related Questions