如何将操作从父视图/组件传递给子组件,同时仍然维护父组件的上下文。下面的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");
}
}
发布于 2015-07-13 15:57:47
如果您真的想这样做(可能有更干净的方法可以这样做),您将需要从您的子视图-模型中访问您的父视图-模型,然后,当调用您的子视图的单击绑定中的方法时,使用.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()
方法的更多信息,请访问莫兹拉的解释
https://stackoverflow.com/questions/31393063
复制相似问题