Jos*_*s11 2 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");
}
}
Run Code Online (Sandbox Code Playgroud)
如果您真的想要这样做(可能有更简洁的方法),您需要从子视图模型访问父视图模型,然后在子视图中单击绑定时调用该方法,用于.call()在do()调用方法时更改方法的范围/上下文.
因此,在您的子视图模型中,首先通过添加以下bind方法来访问父视图模型:
bind( bindingContext ) {
// bindingContext is your parent view-model
this.parent = bindingContext;
}
Run Code Online (Sandbox Code Playgroud)
访问父视图模型后,可以更新子视图中的单击绑定,如下所示:
<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的解释
| 归档时间: |
|
| 查看次数: |
4026 次 |
| 最近记录: |