我正在考虑添加一个“刷新”按钮到一个屏幕,其中有几个奥雷利亚组件。我不希望将其构建到作为刷新目标的组件中。
因此,基本上,我想要重新提取一些web数据,以更新组件时,这个“刷新”按钮被点击。“重新初始化”组件,使构造函数再次运行也是可以接受的。我会将同样的概念应用到我所拥有的几个组件上,如果存在一个模式来泛化地解决这个问题,那将是精妙的。
我设想了一种解决这个问题的解决方案,它以某种方式调用子组件上的一个方法,我可以添加该方法,例如,类似于childcomponent.Refresh()的东西。但是,我不确定如何引用子组件。
处理这种情况的适当方法是什么?
发布于 2016-02-12 20:07:54
有很多方法可以做到这一点,这里有几个选项:
与数据绑定:
app.html
<template>
<button click.delegate="refresh()">Refresh</button>
<component1 data.bind="myData"></component1>
<component2 data.bind="myData"></component2>
<component3 data.bind="myData"></component3>
</template>app.js
export class App {
myData = null;
activate() {
return this.refresh();
}
refresh() {
someService.loadData()
.then(data => this.myData = data);
}
}组件1.js
import {bindable} from 'aurelia-framework';
export class Component1 {
@bindable data;
dataChanged(newValue, oldValue) {
// do something when the data changes...
}
}使用EventAggregator:
app.html
<template>
<button click.delegate="refresh()">Refresh</button>
<component1></component1>
<component2></component2>
<component3></component3>
</template>app.js
import {inject} from 'aurelia-framework';
import {EventAggregator} from 'aurelia-event-aggregator'; // jspm install aurelia-event-aggregator
@inject(EventAggregator)
export class App {
constructor(eventAggregator) {
this.eventAggregator = eventAggregator;
}
activate() {
this.refresh();
}
refresh() {
someService.loadData()
.then(data => this.eventAggregator.publish('data changed', data);
}
}component1.js
import {inject} from 'aurelia-framework';
import {EventAggregator} from 'aurelia-event-aggregator'; // jspm install aurelia-event-aggregator
@inject(EventAggregator)
export class Component1 {
constructor(eventAggregator) {
this.eventAggregator = eventAggregator;
}
dataChanged(data) {
// do something when the data changes...
}
bind() {
this.subscription = this.eventAggregator.subscribe('data changed', data => this.dataChanged(data));
}
unbind() {
this.subscription.dispose();
}
}https://stackoverflow.com/questions/35369418
复制相似问题