我正在使用Aurelia Framework,Typescript并且event aggregator我能够发布和订阅频道.
问题是我无法取消订阅频道.
注意:所有形式的subscribe方法都返回一个dispose函数.您可以调用此函数来处理订阅并停止接收消息.如果由路由器管理,则处置视图模型的停用回调的好地方,或者如果它是任何其他视图模型,则在其分离的回调中.
这取自aurelia官方文档网站,我似乎并不了解如何实现这一点.
我进入了aurelia gitter频道,我找到了3个关于此的讨论,其中一个给出了以下取消订阅的示例:
sub = ea.subscribe();
//unsubscribe the event
sub();
Run Code Online (Sandbox Code Playgroud)
问题是此代码在TypeScript中不起作用.
如何取消订阅event aggregator打字稿?
现在,使用此代码
@inject(Publisher, Subscriber)
export class Home {
publisher: Publisher;
subscriber: Subscriber;
channelName = "testChannel";
constructor(pub: Publisher, sub: Subscriber) {
this.publisher = pub;
this.subscriber = sub;
this.subscriber.subscribe(this.channelName);
this.publisher.publish(this.channelName, "Ana are mere");
}
}
@inject(EventAggregator)
export class Publisher {
eventAggregator: EventAggregator = null;
constructor(agg: EventAggregator) {
this.eventAggregator = agg;
}
publish(channelName: string, …Run Code Online (Sandbox Code Playgroud) 我正在使用app-contacts演示来学习Aurelia,是的我知道,它是不完整的,如@Eisenberg所提到的,但后来当我保存联系人或创建新联系人时,我想使用EventAggregator通知app.js.直到现在一切正常.我能够在app.js中收到联系人对象,但现在我想更新联系人列表,这不起作用,当我保存联系人并更新app.js中的联系人列表时,它将被删除.
在app.js中添加的代码和在构造函数中调用subscribe方法.
subscribe(){
this.ea.subscribe('contact_event', payload => {
console.log(payload);
var instance = JSON.parse(JSON.stringify(payload));
let found = this.contacts.filter(x => x.id == payload.id)[0];
if(found){
let index = this.contacts.indexOf(found);
this.contacts[index] = instance;
}else{
instance.id = this.contacts.length + 1;
this.contacts.push(instance);
}
});
}
Run Code Online (Sandbox Code Playgroud)
没有对app.html进行任何更改
<li repeat.for="contact of contacts" class="list-group-item ${contact.id === $parent.selectedId ? 'active' : ''}">
<a href="#" click.delegate="$parent.select(contact)">
<h4 class="list-group-item-heading">${contact.firstName} ${contact.lastName}</h4>
<p class="list-group-item-text">${contact.email}</p>
</a>
</li>
Run Code Online (Sandbox Code Playgroud)
如何更新列表?
更新 这对我有用,但不确定什么是正确的方法
subscribe(){
this.ea.subscribe('contact_event', payload => {
return this.api.getContactList().then(contacts => {
this.contacts = contacts;
});
});
}
Run Code Online (Sandbox Code Playgroud) 我按照教程http://aurelia.io/hub.html#/doc/article/aurelia/framework/latest/contact-manager-tutorial/1
Everthing看起来很好.但是在我导入EventAggregator(从'aurelia-event-aggregator'导入{EventAggregator};)之后,aurelia没有正确加载它.它是从文件夹dist(编译js文件夹)而不是jspm_packages加载的.
有人知道怎么解决吗?