javascript - 在 Aurelia 中将操作传递给具有父级上下文的组件

标签 javascript ecmascript-6 aurelia

如何将一个 Action 从父 View /组件传递到子组件并仍然保持父组件的上下文。下面的 plunkr 中显示的问题表明,如果操作是在组件中执行的,那么它是在组件的上下文中,而不是传递操作的父级。基本上是典型的“that = this”问题。

是的,您可以使用 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");
    }
}

最佳答案

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

因此,在您的 subview 模型中,首先通过添加以下内容来访问您父 View 模型的 bind方法:

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

访问父 View 模型后,您可以将 subview 中的点击绑定(bind)更新为如下所示:

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

这将调用 do()来自父 View 模型上下文的方法。

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

关于javascript - 在 Aurelia 中将操作传递给具有父级上下文的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31393063/

相关文章:

javascript - 如何将 WebSocket 连接与 Socket.io 事件和 Koa Rest api 结合使用?

javascript - 将切换按钮替换为复选框但不起作用

javascript - 使用 Javascript 扩展侧边栏高度以等于内容高度

javascript - 在 Promise.all 的响应中命名对象?

reactjs - 在 react 中访问类内的状态

typescript - Aurelia Typescript http-fetch-client异步捕获不起作用

javascript - JavaScript 变量如何工作?

javascript - 在react js中使用map重复带有键和值的数组对象

javascript - 无法调用 jQuery

azure-devops - Aurelia 在 VSO 托管构建 Controller 上构建