Open In App

Ember.js Component cacheFor() Method

Last Updated : 02 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Ember.js is an open-source JavaScript framework used for developing large client-side web applications which is based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity. Currently, it is utilized by a large number of websites, including Square, Discourse, Groupon, Linked In, Live Nation, Twitch, and Chipotle.

The cacheFor() Method of the Component method is used to get the cached value of the computed property if it exists else invoke the computed property. 

Syntax: 

this.object.cacheFor( PropertyName );

 

Parameters: 

  • PropertyName: The name of the computed property whose store cache value we want. 

Returns: It returns the cached value of the computed property. 

Steps to Install and Run Ember.js:

Step 1: To run the following examples, you need to have an ember project. To create one, you will need to install ember-cli first. Write the below code in the terminal:

npm install ember-cli

Step 2: Now, you can create the project by typing in the following piece of code:

ember new <project-name> --lang en

To start the server, type:

ember serve

Example 1: Type the following code to generate the route for this example:

ember generate route temp1

app/components/second.js

Javascript




import Component from '@glimmer/component';
import Ember from 'ember';
import EmberObject from '@ember/object';
import { action, without, set, get, computed } from '@ember/object';
  
const Student = EmberObject.extend({
    fullName: computed('firstName', 'lastName', {
        get() {
            return `${this.firstName} ${this.lastName}`;
        }
    }),
  
    toStringExtension() {
        return this.get('fullName');
    },
});
export default Ember.Component.extend({
    students: [
        Student.create({
            firstName: 'Sam',
            lastName: 'Snehil',
            Marks: 72,
            class: 11,
        }),
        Student.create({
            firstName: 'Ram',
            lastName: 'Sahu',
            Marks: 84,
            class: 10,
        }),
        Student.create({
            firstName: 'Soham',
            lastName: 'Verma',
            Marks: 69,
            class: 12,
        }),
        Student.create({
            firstName: 'David',
            lastName: 'Tigga',
            Marks: 53,
            class: 9,
        }),
        Student.create({
            firstName: 'Pokhu',
            lastName: 'Verma',
            Marks: 95,
            class: 10,
        }),
        Student.create({
            firstName: 'Satyam',
            lastName: 'Verma',
            Marks: 75,
            class: 12,
        }),
    ],
  
     @action
    StoreName(data) {
  
         this.students.forEach(function (item) {
            if (item.fullName == data) {
  
            let temp = item.cacheFor('fullName');
            console.log(`${temp} is stored from ${item.toString()}`)
  
        }
    })
}
    })


app/components/second.hbs

HTML




{{page-title "Component cacheFor"}}
<h3>List of Item in Buckets</h3>
<table>
    <tr>
        <th> Name </th>
        <th>Class </th>
        <th>Marks </th>
    </tr>
    {{#each this.students as |temp|}}
    <tr>
        <td>{{temp.fullName}}</td>
        <td>{{temp.class}}</td>
        <td>{{temp.Marks}}</td>
    </tr>
    {{/each}}
</table>
<br />
<div>
    <label>Enter Name : </label>
    {{input value=this.item}}
</div><br />
  
<input type="button"
       id="Cache-property" 
       value="Store the Computed Property"
      {{action "StoreName" this.item}} />
<br /><br />
{{outlet}}


app/templates/temp1.hbs

HTML




<Second>
     Example of Components cacheFor method
</Second>


Output:

output1

Example 2: In the following example we will see the laziness of the computed property. We see the output in the console whenever the computed property is called. And when we retrieve the cached value of the property see computed property is not called. 

Type the following code to generate the route for this example:

ember generate route temp2

app/components/first2.js

Javascript




import Component from '@glimmer/component';
import Ember from 'ember';
import EmberObject from '@ember/object';
import { action, without, set, get, computed} from '@ember/object';
  
let value = 0; 
const Student = EmberObject.extend({
    describeSkill: computed('Name', 'skill',{
        get() {
                console.log('Computed property called for ', this.Name, value+=1)
                return `${this.Name} knows ${this.skill} language`;
              }
            }),
  
    toStringExtension() {
                return this.get('Name');
            },
    });
export default Ember.Component.extend({
    students : [
        Student.create({
            Name: 'Balit',
            skill: 'Python',
            Id: 'stu2',
          
        }),
        Student.create({
            Name: 'Arabh',
            skill: 'c++',
            Id: 'stu5',
        }),
        Student.create({
            Name: 'Tanu',
            skill: 'Java',
            Id: 'stu4',
        }),
        Student.create({
            Name: 'Pokhu',
            skill: 'JavaScript',
            Id: 'stu3',
        }),
        Student.create({
            Name: 'Sam',
            skill: 'R',
            Id: 'stu1',
        }),
        Student.create({
            Name: 'Permu',
            skill: 'PHP',
            Id: 'stu0',
        }),
    ],
  
    @action
    StoreName(data) {
        this.students.forEach( function(item){
                if(item.Name == data ){
  
                    item.describeSkill
                    let temp = item.cacheFor('describeSkill');
                    console.log(`'${temp}' is stored from ${item.toString()}`)
  
                
        })
    }
  
    })


app/components/first2.hbs

HTML




{{page-title "Component cacheFor"}}
<h3>List of Item in Buckets</h3>
<table>
    <tr>
        <th> Name </th>
        <th>Skill </th>
        <th>Id </th>
    </tr>
    {{#each this.students as |temp|}}
    <tr>
        <td>{{temp.Name}}</td>
        <td>{{temp.skill}}</td>
        <td>{{temp.Id}}</td>
    </tr>
    {{/each}}
</table>
<br />
<div>
    <label>Enter Name : </label>
    {{input value=this.item}}
</div><br />
  
<input
    type="button"
    id="Cache-property"
    value="Store the Computed Property"
    {{action "StoreName" this.item}}
/>
<br /><br />
{{outlet}}


app/templates/temp2.js

HTML




<First>
    Example of Component cacheFor method
</First>


Output: Here in output we can see computed property is only called once. 

output2

Reference: https://api.emberjs.com/ember/4.9/classes/Component/methods/cacheFor?anchor=cacheFor



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads