从中继器循环中显示的子自定义元素获取正确的上下文.奥蕾莉亚

Get correct context from child custom element which displays in repeater loop. Aurelia

本文关键字:上下文 获取 元素 循环 中继器 显示 自定义      更新时间:2023-09-26

>我有父模板,它有一个用于子自定义元素的中继器。

<!-- users.html -->
<div class="col-sm-6 col-md-3" repeat.for="user of users">
    <git-hub-user-card user.bind="user" edit-user.bind="editUser"></git-hub-user-card>
</div>

editUser是位于父 VM 中的回调,我需要从我的子自定义元素调用它。

这是我的孩子自定义组件

/*user.js*/
import {customElement, bindable} from 'aurelia-framework';
    @customElement('git-hub-user-card')
    export class GithubUser {
        @bindable editUser;
        @bindable user = {};
        bind(parentCtx) {
            this.$parentCtx = parentCtx;
        }
    }

这是子模板

<!-- user.html -->
<div class="content">
   <p class="name" >${user.login}</p>
   <a href="#" class="btn btn-default" click.delegate="editUser.call($parentCtx, $event, user)">Edit Name</a>
 </div>

因此,我已通过绑定在子组件中传递了回调函数。

<git-hub-user-card user.bind="user" edit-user.bind="editUser"></git-hub-user-card>

我的第一个问题:可以吗?或者有一些更简洁的方法可以从子组件调用回调?

然后我尝试在子虚拟机中获取父虚拟机上下文:

bind(parentCtx) {
  this.$parentCtx = parentCtx;
}

并尝试将回调调用绑定到此上下文:

<a click.delegate="editUser.call($parentCtx, $event, user)">Edit Name</a>

但是在这种情况下$parentCtx不正确,因为父模板中repeat.for$parentCtx等于我的GithubUser。如何在父虚拟机中获取 editUser 的正确上下文?我应该用边界来路径吗?

users.html模板中使用call绑定命令。当调用该方法时,它将保留正确的上下文/this。如下所示:

用户.js

import {customElement, bindable} from 'aurelia-framework';
@customElement('git-hub-user-card')
export class GithubUser {
  @bindable editUser;
  @bindable user;
}

用户.html

<div class="content">
  <p class="name" >${user.login}</p>
  <a href="#" class="btn btn-default" click.delegate="editUser()">Edit Name</a>
</div>

用户.html

<div class="col-sm-6 col-md-3" repeat.for="user of users">
  <git-hub-user-card user.bind="user" edit-user.call="editUser(user)"></git-hub-user-card>
</div>