Ecmascript 6 在Aurelia中将数据从一个视图模型传递到另一个视图模型
我有一个名为Ecmascript 6 在Aurelia中将数据从一个视图模型传递到另一个视图模型,ecmascript-6,aurelia,Ecmascript 6,Aurelia,我有一个名为entry main的页面,其中包括以下模板: <template> <entry-search></entry-search> <entry-details></entry-details> </template> 我现在的问题是,如何从我的条目详细信息视图模型中的typeahead视图模型中获取this.selected? 为了清楚起见,它应该是这样的: <template>
entry main
的页面,其中包括以下模板:
<template>
<entry-search></entry-search>
<entry-details></entry-details>
</template>
我现在的问题是,如何从我的条目详细信息视图模型中的typeahead视图模型中获取this.selected
?
为了清楚起见,它应该是这样的:
<template>
<div class="row">
<div class="col-lg-12">
<div class="input-group">
<span id="entry_search" class="input-group-addon">
<span class="fa fa-search"></span>
</span>
<!-- important part -->
<typeahead id="choose" placeholder="Holding the place"></typeahead>
<!-- end of important part -->
</div>
</div>
</div>
</template>
$(this.id).on('typeahead:selected', function (e, item) {
this.selected = item;
});
<entry-main>
<entry-search>
<typeahead></typeahead>
</entry-search>
<entry-details>
${selected}
</entry-details>
</entry-main>
${selected}
您可以这样做:
在条目主目录中创建属性“选定”:
export class EntryMain {
selected = '';
//rest of the code
}
在typeahead
中创建可绑定属性:
import { bindable } from 'aurelia-framework';
export class Typeahead {
@bindable selected;
//... rest of the code
}
将typeahead的“selected”绑定到entry main的“selected”
${selected}
未经测试的代码,但我认为它应该可以工作。正如@JorisDecraecker所说,可以使用EventAggregator
完成。可根据需要修改的示例代码:
app.html
<template>
<button click.delegate = "publish()">PUBLISH</button><br/>
<button click.delegate = "subscribe()">SUBSCRIBE</button><br/>
<button click.delegate = "dispose()">DISPOSE</button>
</template>
资料来源:
这实际上是可行的。虽然我自己没有测试过,但我使用了Aurelia的EventAggregator
。这样我就可以轻松地将数据从任何viewmodel传递到任何其他随机viewmodel。嘿,@JorisDecraecker,太棒了!你绝对应该把它作为一个答案发布。为什么这对我不起作用?我没有使用自定义元素,有必要吗?有。此解决方案仅适用于自定义图元。如果您不想使用它们,可以在第一条注释中检查解决方案。
<template>
<button click.delegate = "publish()">PUBLISH</button><br/>
<button click.delegate = "subscribe()">SUBSCRIBE</button><br/>
<button click.delegate = "dispose()">DISPOSE</button>
</template>
import {inject} from 'aurelia-framework';
import {EventAggregator} from 'aurelia-event-aggregator';
@inject(EventAggregator)
export class App {
constructor(eventAggregator) {
this.eventAggregator = eventAggregator;
}
publish() {
var payload = 'This is some data...';
this.eventAggregator.publish('myEventName', payload);
}
subscribe() {
this.subscriber = this.eventAggregator.subscribe('myEventName', payload => {
console.log(payload);
});
}
dispose() {
this.subscriber.dispose();
console.log('Disposed!!!');
}
}