Open In App

Ember.js Helper willDestroy() Method

Last Updated : 30 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Ember.js is a JavaScript framework for building web applications. One of the features of Ember.js is the use of helpers, which are functions that can be used in templates to perform specific tasks or calculations. The willDestroy() method is a lifecycle hook that is called when an Ember component is about to be destroyed.

The willDestroy() method is called just before a component is removed from the DOM, allowing the component to perform any necessary cleanup tasks, such as stopping timers or unsubscribing from events.

Syntax:

willDestroy() {
     // Cleanup code goes here
}

 

Parameters:

  • keyName.The name of the property whose value we desire is keyName.

Return Value: Undefined or the value of the property.

Steps to Install:

Step 1: Install Node.js and npm (Node Package Manager) if they are not already installed on your system.

Step 2: Install the Ember CLI (Command Line Interface) by running the following command in the terminal: 

npm install -g ember-cli

Step 3: Create a new Ember.js project by running the command

 ember new <project-name>

Step 4: Change into the project directory

cd <project-name>

Step 5: Start the development server with ember serve. Visit the application at in your web browser.

http://localhost:4200

Example 1:

Javascript




import Component from '@ember/component';
import Helper from '@ember/component/helper';
  
export default class MyHelper extends Helper {
    compute() {
        // Do something
    }
  
    willDestroy() {
        // Clean up resources
    }
}
  
export default Component.extend({
    timer: null,
  
    didInsertElement() {
        this.timer = setInterval(() => {
            console.log('Timer running');
        }, 1000);
    },
  
    willDestroy() {
        clearInterval(this.timer);
    }
});


In this example, the compute method is used to perform some computation and the willDestroy method is used to clean up any resources that the helper has established.

 

Example 2: 

Javascript




import Helper from '@ember/component/helper';
  
export default class MyHelper extends Helper {
    constructor() {
        super(...arguments);
        this.myConnection = new WebSocket('ws://...com');
    }
  
    compute() {
        return this.myConnection.status;
    }
  
    willDestroy() {
        this.myConnection.close();
    }
}


 

Reference: https://api.emberjs.com/ember/release/classes/Helper/methods



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads