将操作传递给Aurelia中父级上下文的组件

时间:2015-07-13 20:42:15

标签: javascript ecmascript-6 aurelia aurelia-binding

如何将操作从父视图/组件传递到子组件,并仍然维护父组件的上下文。下面的plunkr中显示的问题表明,如果操作在组件中执行,则它位于组件的上下文中,而不是传递操作的父级。基本上是典型的"那="问题。

是的,您可以使用eventAggregator来执行此操作,但如果没有它,您会怎么做?您是否必须将整个viewModel传递给组件?

http://plnkr.co/edit/n1xPUdR5nhXwwIivawBj?p=preview

// app.js
import { inject } from 'aurelia-framework';
import { MyService } from './my-service';

@inject(MyService)
export class App {
    constructor(myService) {
        this.myService = myService;
        this.message = "Hello World!";
    }

    doThing() {
        console.log('do a thing');
        this.myService.foo();
    }
}

<!--app.html-->
<template>
    <require from="./my-component"></require>
    <p>${message}</p>
    <button click.delegate="doThing()">Do the thing - in app.html</button>
    <my-component do.bind="doThing"></my-component>
</template>

// my-component.js
import { bindable } from 'aurelia-framework';

@bindable('do')
export class MyComponentCustomElement {

}

<!-- my-component.html -->
<template>
    <button click.delegate="do()">Do the thing - in my-component</button>
</template>

// my-service.js
export class MyService {
    foo() {
        alert("pity da foo");
    }
}

1 个答案:

答案 0 :(得分:5)

如果您真的想要这样做(可能有更简洁的方法),您需要从您的子视图模型访问您父视图模型,然后在调用时在您的子视图的点击绑定方法中,使用.call()更改do()方法的范围/上下文。

因此,在您的子视图模型中,首先通过添加以下bind方法来访问您父视图模型:

bind( bindingContext ) {
    // bindingContext is your parent view-model
    this.parent = bindingContext;
}

在您访问父视图模型后,您可以更新子视图中的单击绑定,如下所示:

<button click.delegate="do.call( parent )">Do the thing - in my-component</button>

这将从父视图模型的上下文中调用do()方法。

您可以使用.call( scope/context, list, of, args, ... ).apply( scope/context, [array of args])。有关.call()方法的详细信息,请查看Mozilla's explanation