Open In App

Ember.js Controller Class

Last Updated : 24 Jan, 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.

Controller Class:

In Ember.js, you can add display logic to your models using controllers. Models typically have attributes that need to be saved to the server, whereas controllers typically have properties that your app can ignore saving to the server.

 

Methods: The following is the list of methods for this class:

  • addObserver: This method registers an observer to the property and the Observer notify whenever the value of the property changes. 
  • cacheFor: This method is used to get the cached value for an already computed property if it exists.
  • create: This method creates a class instance.
  • decrementProperty: This method is used to set the value of the property to the current value minus some amount.
  • destroy: This method destroys an object by setting the isDestroyed flag and deleting its metadata.
  • extend: This method creates a new subclass.
  • get: This method is used to retrieve the value of a property from the object.
  • getProperties: This method is used to get the value of multiple properties at once.
  • getWithDefault: This method obtains the value of a property or, in the event that the property returns an undefined, default value.
  • incrementProperty: This method is used to set the value of the property to the current value plus some amount.
  • init: This method is the method that is called whenever the object is created. 
  • notifyPropertyChange: This method alerts the observer system that a property change has taken place.
  • removeObserver: This  method removes any observers you have registered earlier for this object.
  • reopen: This method adds further features and characteristics to a constructor’s prototype.
  • reopenClass: This method increases a constructor’s own features and capabilities.
  • replaceRoute: This method will, if possible, switch to a different route and remove the old one.
  • send: This method causes the ActionHandler’s designated action to be triggered.
  • set: This method is used to set the key and value or new value to the existing key to the object.
  • setProperties: This method sets a number of properties at once.
  • toString: This method is to get the string representation of the object. 
  • toggleProperty: This method is used to set the value of the boolean property to the opposite of its current value.
  • transitionToRoute: This method switches the application to a different path.
  • willDestroy: This method tears down the object.

Properties: The following is the list of the properties of this class:

  • actions: This is the list of actions that can be taken using the functions that are available on this ActionHandler, keyed by name.
  • concatenatedProperties: This  property specifies the characteristics from the superclass that will be concatenated
  • isDestroyed: This property is the destroy complete flag.
  • isDestroying: This  property is the destroy scheduled flag.
  • mergedProperties: This property helps to merge the value of the subclass property’s value with the superclass property value of the ember class.
  • model: This is the current model of the controller.
  • queryParams: This property establishes the query parameters that the controller will accept.
  • target: This is the thing that should receive actions from the view.

Step 1: To run the following examples you will need to have an ember project with you. 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: In this example, I am going to demonstrate the use of the function getProperties of the class.

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

ember generate route fruits

app/routes/fruits.js

Javascript




import Route from '@ember/routing/route';
  
export default class FruitsRoute extends Route {
    fruits = [
        {
            'name': 'Lady Finger',
            'isFruit': false,
            'color': 'green'
        },
        {
            'name': 'Brinjal',
            'isFruit': false,
            'color': 'purple'
        },
        {
            'name': 'Apple',
            'isFruit': true,
            'color': 'red'
        },
        {
            'name': 'Grapes',
            'isFruit': true,
            'color': 'green'
        },
        {
            'name': 'Mango',
            'isFruit': true,
            'color': 'yellow'
        },
        {
            'name': 'Watermelon',
            'isFruit': true,
            'color': 'red'
        },
        {
            'name': 'Orange',
            'isFruit': true,
            'color': 'orange'
        }
    ];
    item2;
    item3;
  
    model() {
        this.set('[]', this.fruits)
        return this;
    }
    setupController(controller, model) {
        super.setupController(controller, model);
        controller.set('fruits', this.fruits);
    }
}


app/controllers/fruits.js

Javascript




import Ember from "ember";
import { addObject, isAny, isEvery } from "@ember/array";
import EmberObject from '@ember/object';
  
const Fruit = EmberObject.extend({
    init() {
        alert(`${this.getProperties('name').name}
        is Added in list`);
    }
});
export default Ember.Controller.extend({
    actions: {
        list() {
            let list = '';
            this.fruits.map((item) => list +=
                item.name + ` is ${item.color}` + '\n');
            alert(list)
        },
        insertItem(data, data1, data2) {
            let temp = Fruit.create({
                name: data,
                isFruit: data1,
                color: data2
            });
            this.fruits.addObject(temp);
        }
    },
});


app/template/fruits.hbs

HTML




<h3>List of Fruits:</h3>
<table>
    <tr>
        <th>Name</th>
        <th>Fruit</th>
        <th>Color</th>
    </tr>
    {{#each this.fruits as |detail|}}
        <tr>
            <td>{{detail.name}}</td>
            <td>{{detail.isFruit}}</td>
            <td>{{detail.color}}</td>
        </tr>
    {{/each}}
</table>
  
<br /><br />
<div>
    <label>Enter Fruit Name: </label>
    {{input value=this.item1}}
</div><br />
<div>
    <label>Item is Fruit: </label>
    {{input value=this.item2}}
</div><br />
<div>
    <label>Enter Fruit color: </label>
    {{input value=this.item3}}
</div><br />
<div>
    <input
        type="button"
        id="insert-item"
        value="Insert Furit"
        {{action "insertItem" this.item1 this.item2 this.item3}}
    />
</div>
<br />
<div>
    <input
        type="button"
        id="list-item"
        value="Print Items"
        {{action "list"}}
    />
</div>
{{outlet}}


Output:

 

Example 2: In this example, I am going to demonstrate the use of the function init of the class.

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

ember generate route party

app/routes/party.js

Javascript




import Route from '@ember/routing/route';
  
export default class PartyRoute extends Route {
    p1 = [
        'Digital Camera',
        'Jugs, cups & straws',
        'Balloons',
        'Scissors',
        'Cold Drink',
        'Table',
    ];
    model() {
        return this.p1;
    }
    setupController(controller, model) {
        super.setupController(controller, model);
        controller.set('p1', this.p1);
    }
}


app/controllers/party.js

Javascript




import Ember from 'ember';
  
export default Ember.Controller.extend({
    value: 'value',
    init() {
        this._super(...arguments);
        this.addObserver('value', this, 'Change');
        alert('Controller Init() is initiated');
    },
  
    Change() {
        console.log('value changed');
    },
    actions: {
        remove(data) {
            this.p1.set('[]', this.p1.without(data));
        },
        print() {
            let ans = this.p1.set('[]');
            alert(ans.join('\n'));
        },
    },
});


app/template/party.hbs

HTML




<ul>
    <h3>List is : </h3>
    {{#each @model as |party|}}
    <li>{{party}}</li>
    {{/each}}
</ul>
<br />
{{input value=this.value}}
<br />
<input type="button" 
       id="check-atIndex" 
       value="Remove" {{action "remove" this.value}} />
<br /><br />
<input type="button" 
       id="print-item"
       value="Print All Items" 
       {{action "print" this.value}} />


Output:

 

Reference: https://api.emberjs.com/ember/2.15/classes/Ember.Controller



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads