Aurelia的视图模型类中是否有一些析构函数或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);
}
}
我希望在视图即将被销毁时杀死计时器。
答案 0 :(得分:4)
将attached
和detached
view lifecycle挂钩添加到您的视图模型中,以选择在发生这些事件时收到通知。
created(view:View)
- 在创建视图和视图模型后调用。允许您的行为直接访问View实例。bind(bindingContext:any)
- 在数据绑定引擎绑定视图时调用。绑定上下文是视图数据绑定到的实例。unbind()
- 在数据绑定引擎取消绑定视图时调用。attached()
- 当包含扩展名的视图附加到DOM时调用。detached()
- 当包含扩展名的视图与DOM分离时调用。
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);
}
}