简体   繁体   中英

Is there any destructor in Aurelia's view-model classes?

Is there some destructor or Dispose method in Aurelia's view-model classes? Basically I have following code:

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);
  }
}

I would like to kill timer when view is about to be destroyed.

Add the attached and detached view lifecycle hooks to your view model to opt into being notified when those events occur.

  • created(view:View) - Invoked after both the view and view-model have been created. Allows your behavior to have direct access to the View instance.
  • bind(bindingContext:any) - Invoked when the databinding engine binds the view. The binding context is the instance that the view is databound to.
  • unbind() - Invoked when the databinding engine unbinds the view.
  • attached() - Invoked when the view that contains the extension is attached to the DOM.
  • detached() - Invoked when the view that contains the extension is detached from the DOM.

http://aurelia.io/docs.html#extending-html

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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM