Aurelia(アウレリア)の勉強をしています。
http://aurelia.io/
チュートリアル
http://aurelia.io/hub.html#/doc/article/aurelia/framework/latest/contact-manager-tutorial/1
前回のつづき
今回は、イベント関係の部分。
messages.js
export class ContactUpdated {
constructor(contact){
this.contact = contact;
}
}
export class ContactViewed {
constructor(contact){
this.contact = contact;
}
}
EventAggregator は、アウレリアのイベント関係の機能。
リストから選択(ContactViewed)されたとき、詳細情報が更新(ContactUpdated)されたときに、メッセージを発行する(publish)。
contact-detail.js
import {EventAggregator} from 'aurelia-event-aggregator';
import {WebAPI} from './web-api';
import {ContactUpdated,ContactViewed} from './messages';
import {areEqual} from './utility';
export class ContactDetail {
static inject = [WebAPI, EventAggregator];
constructor(api, ea){
this.api = api;
this.ea = ea;
}
activate(params, routeConfig) {
this.routeConfig = routeConfig;
return this.api.getContactDetails(params.id).then(contact => {
this.contact = contact;
this.routeConfig.navModel.setTitle(contact.firstName);
this.originalContact = JSON.parse(JSON.stringify(contact));
this.ea.publish(new ContactViewed(this.contact));
});
}
get canSave() {
return this.contact.firstName && this.contact.lastName && !this.api.isRequesting;
}
save() {
this.api.saveContact(this.contact).then(contact => {
this.contact = contact;
this.routeConfig.navModel.setTitle(contact.firstName);
this.originalContact = JSON.parse(JSON.stringify(contact));
this.ea.publish(new ContactUpdated(this.contact));
});
}
canDeactivate() {
if(!areEqual(this.originalContact, this.contact)){
let result = confirm('You have unsaved changes. Are you sure you wish to leave?');
if(!result){
this.ea.publish(new ContactViewed(this.contact));
}
return result;
}
return true;
}
}
.subscribeで、イベント発生時の処理を記述。
contact-list.js
import {EventAggregator} from 'aurelia-event-aggregator';
import {WebAPI} from './web-api';
import {ContactUpdated, ContactViewed} from './messages';
export class ContactList {
static inject = [WebAPI, EventAggregator];
constructor(api, ea){
this.api = api;
this.contacts = [];
ea.subscribe(ContactViewed, msg => this.select(msg.contact));
ea.subscribe(ContactUpdated, msg => {
let id = msg.contact.id;
let found = this.contacts.find(x => x.id === id);
Object.assign(found, msg.contact);
});
}
created(){
this.api.getContactList().then(contacts => this.contacts = contacts);
}
select(contact){
this.selectedId = contact.id;
return true;
}
}
Object.assign(found, msg.contact);
msg.contactを、foundにコピーする。
0 件のコメント:
コメントを投稿