Aurelia:从子 VM 中访问父 VM 方法

Aurelia: Accessing parent VM method from within child VM

使用列表的一个常见用例是从列表项中访问列表的方法。例如:项目项可以选择从包含列表中删除自己。我想知道我在下面为 Aurelia 描述的模式是否有效,或者是否有更好的解决方案。

在 Aurelia 中,我有以下设置:

包含列表:(project-list.html and projectList.js)

<template>      
  <div class="projects">
    <input value.bind="newProjectName" placeholder="New project name"/>
    <project-item repeat.for="project of projects" project.bind="project"></project-item>
  </div>
</template>

和子项:(project-item and projectItem.js)

<template>
  <span class="title">
    ${project.name} <i click.delegate="deleteProject(project)" class="icon-trash"></i>
  </span>
</template>

在这种情况下 deleteProject(project) 是 projectList VM 的成员:

function deleteProject(project){
    var index = this.projects.indexOf(project);
    if (index>-1){
        this.projects.splice(index,1)
    }
}

不幸的是,据我了解这个问题https://github.com/aurelia/framework/issues/311, 那将不再起作用。

作为解决方法,我可以在项目项 VM 上绑定一个函数:

@bindable delete: Function;

并在项目列表模板中:

<project-item repeat.for="project of projects" project.bind="project" delete.bind="deleteProject"></project-item>

这确实有效,前提是绑定函数是一个赋值的 属性 和一个闭包:

deleteProject = function(project : Projects.Project){
        var index = this.projects.indexOf(project);
        if (index>-1){
            _.remove(this.projects,(v,i)=>i==index);
        }
    }

需要闭包才能访问正确的上下文(this 是项目列表)。使用

function deleteProject(project)

this 将引用项目项的上下文。

尽管这种结构可行并且在管道方面没有太多开销,但我觉得它有点脆弱:

或者我可能缺少一个 Aurelia 冒泡机制,该机制可以访问由框架处理的父虚拟机?

回答后编辑: 根据@Sylvain 的回答,我制作了一个 GistRun,它通过添加和删除实现了骨架列表和列表项实现:

Aurelia Skeleton list list-item implementation

这里有一些传递函数引用的替代方法:

  • 让子组件使用 EventAggregator 单例实例广播 public 事件,并让父组件对事件做出反应

  • 让子组件使用私有 EventAggregator 实例广播私有事件,并让父组件对事件做出反应

  • 让子组件广播一个 DOM 事件并用 delete.call 将它绑定到父组件,像这样 <project-item repeat.for="project of projects" project.bind="project" delete.call="deleteProject($even t)"></project-item>

我个人的偏好是第三种选择。我觉得更像是 "Web Components"。