Aurelia的 View 模型类中是否有某些析构函数或Dispose方法?基本上我有以下代码:
import {apiFetchClient} from 'common/restClient/apiFetchClient';
import {json} from 'aurelia-fetch-client';
import {inject} from 'aurelia-framework';
@inject(apiFetchClient)
export class BetsList {
constructor(apiFetchClient){
var timer = setInterval(()=>this._fetchBets(), 1000);
this.apiFetchClient = apiFetchClient;
this.betSystems = [];
this._fetchBets();
}
_fetchBets(){
this.apiFetchClient
.fetch('/bets')
.then(response => response.json())
.then(data => this.betSystems = data);
}
}
当 View 即将被销毁时,我想杀死计时器。
最佳答案
将attached
和detached
view lifecycle挂钩添加到您的 View 模型,以选择在发生这些事件时被通知。
import {apiFetchClient} from 'common/restClient/apiFetchClient';
import {json} from 'aurelia-fetch-client';
import {inject} from 'aurelia-framework';
@inject(apiFetchClient)
export class BetsList {
constructor(apiFetchClient){
this.apiFetchClient = apiFetchClient;
this.betSystems = [];
this._fetchBets();
}
_fetchBets(){
this.apiFetchClient
.fetch('/bets')
.then(response => response.json())
.then(data => this.betSystems = data);
}
attached() {
this.interval = setInterval(() => this._fetchBets(), 1000);
}
detached() {
clearInterval(this.interval);
}
}