Aurelia:渲染从转发器中的服务器获取的对象,并将它们与父级绑定

时间:2016-08-01 17:38:55

标签: typescript aurelia aurelia-binding

我正在尝试从服务器获取对象列表(JSON),然后在转发器中呈现它们,并在每个要由父视图模型处理的项目上有一个单击处理程序。到目前为止,我有:

/* 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>

然后是玩家自定义元素:

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

玩家模特:

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

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

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

当我从服务器接收数据时:

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);
      }
  });

其中this.players是list.ts视图模型中的数组属性。

我有两个问题:

  1. bind上的PlayerModel方法未触发 - 为什么?
  2. 我无法使用dosth功能。我得到'dosth'不是函数错误。
  3. 有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:2)

您正在加载仅限HTML的自定义元素。如果您有视图模型(在您的情况下为player.ts),则必须要求不包含.html的自定义元素。像这样:

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

此外,html标记中的containerless仅适用于仅支持html的自定义元素。在您的情况下,您必须在视图模型中声明containerless。像这样:

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

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

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

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

的更多信息