Create a class to contain your shared state and take a dependency on that class in your view-models. You can use the NewInstance.of
resolver to control when shared state is created vs reused.
Here's an example: https://gist.run?id=4cbf5e9fa71ad4f4041556e4595d3e36
shared-state.js
export class SharedState {
fromdate = '';
todate = '';
language = 'English';
}
shared-parent.js
import {inject, NewInstance} from 'aurelia-framework';
import {SharedState} from './shared-state';
@inject(NewInstance.of(SharedState)) // <-- this says create a new instance of the SharedState whenever a SharedParent instance is created
export class SharedParent {
constructor(state) {
this.state = state;
}
configureRouter(config, router){
config.title = 'Aurelia';
config.map([
{ route: ['', 'child-a'], moduleId: './child-a', nav: true, title: 'Child A' },
{ route: 'child-b', moduleId: './child-b', nav: true, title: 'Child B' },
]);
this.router = router;
}
}
note: if you use @inject(SharedState)
instead of @inject(NewInstance.of(SharedState))
, a single instance of SharedState
will be shared with all components. This may be what you are looking for, I wasn't sure. The purpose of @inject(NewInstance.of(SharedState))
is to make sure the parent and it's children have their own SharedState
instance.
child-a.js
import {inject} from 'aurelia-framework';
import {SharedState} from './shared-state';
@inject(SharedState)
export class ChildA {
constructor(state) {
this.state = state;
}
}
child-b.js
import {inject} from 'aurelia-framework';
import {SharedState} from './shared-state';
@inject(SharedState)
export class ChildB {
constructor(state) {
this.state = state;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…