Open In App

Ember.js Transition Class

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

Ember.js is originally a JavaScript framework that is used for building web applications. In the Ember.js there is one of the features which has the ability to handle transitions between routes, which can be used to add animations and other visual effects to the changes in the application’s state.

The Transition class is basically a primary API that is used to work with route transitions in Ember.js.

It has several methods and properties that can be used to access and manipulate the transition. with help of these properties, we can simplify our work while working in Ember.js.

This can enhance the user experience by adding animations, spinners, and conditional navigation, and also by making the navigation between routes feel more smooth and more polished, transition class in Ember.js is a powerful tool.

Methods: The following are the methods used in the transition class of Ember.js:

  • transitionTo(routeName, models, options): Use to navigate to a new route(new page), passing along any models as the parameters.
  • retry(): This method is used to retry(trying for following the transition again) the transition that failed previously.
  • abort(): It is used to stop the transition and roll back any changes that have been made so far. It basically returns the database to some previous state.

Properties: Here are some properties of the transition class of Ember.js

  • isAborted: This is a boolean property that indicates whether the transition has been stopped by using the abort() method
  • isActive: This property is a boolean that indicates whether the transition is currently in progress.
  • isExiting: This boolean property returns true or false whether the current route is being exited as part of the transition.
  • isEntered: whether the new route has been entered as part of the transition.

Events: These events invoke interaction to elements where they are applied, following are the examples:

  • willTransition: This event fired(launch)before the transition starts.
  • didTransition: It is the opposite of willTransition which fired after the transition is complete.
  • loading: fired when the transition is in the loading state.

Creating Ember.js Application:

Step 1: Write the below command in the terminal:

npm install -g ember-cli

Step 2: Create a new Ember.js application by running the command.

ember new my-app

This will create a new directory called “my-app” with the basic file structure for an Ember.js application.

Step 3: In the “my-app” directory, create a new route using this command.

ember generate route protected

Step 4: This step will create a new directory called “login” in the “routes” directory with a template, controller, and route file. follow this command to do that 

ember generate route login

Step 5: Replacing the contents of the “protected” template file with the HTML code

Example 1: In this example, we are using the willTransition action to handle a transition to a different route when the user is not logged in. If the user is not logged in, the action will ask the user if they want to login and if they confirm, the action will transition to the login route. If the user does not confirm, the action will abort the transition.

app/templates/protected.hbs

HTML




<div class="content">
    <h1>GeeksforGeeks</h1>
    <h1>Welcome to the Protected Route</h1>
    <p>You need to login first to see this content.</p>
</div>


app/templates/login.hbs

HTML




<div class="login">
    <h1>GeeksforGeeks</h1>
    <form>
        <label>Username: 
              <input type="text" 
                   {{action "login" on="submit" }}></label>
        <label>Password: 
              <input type="password" 
                   {{action "login" on="submit" }}></label>
        <button type="submit">Login</button>
    </form>
</div>


app/routes/protected.js

Javascript




import Ember from 'ember';
  
const { Route, Transition } = Ember;
  
export default Route.extend({
    actions: {
        willTransition(transition) {
            let token = this.controller.get('token');
            if (!token) {
let login = confirm("You need to login first. Do you want to login now?");
                if (login) {
                    this.transitionTo('login');
                } else {
                    transition.abort();
                }
            }
        }
    }
});


app/controllers/login.js

Javascript




import Ember from 'ember';
  
export default Ember.Controller.extend({
    token: null,
  
    actions: {
        login() {
            let username = this.get('username');
            let password = this.get('password');
  
            // authenticate user
            let token = authenticate(username, password);
            if (token) {
                this.set('token', token);
                this.transitionToRoute('protected');
            } else {
                alert("Invalid username or password");
            }
        }
    }
});


Step 6: Adding the routes for the protected and login pages

app/router.js

Javascript




import Ember from 'ember';
import config from './config/environment';
  
const Router = Ember.Router.extend({
    location: config.locationType,
    rootURL: config.rootURL
});
  
Router.map(function () {
    this.route('protected');
    this.route('login');
});
  
export default Router;


Step 7: Start the Ember.js development server

ember serve

Now open a web browser and navigate to http://localhost:4200. You should see the login template, fill the form and submit it, then the protected template should be displayed if the user is authenticated successfully.

Output:

Output

Example 2: In this example, we are using the willTransition action to handle a transition to a different route. The action is passed a Transition object, which we can use to abort the transition if the user decides not to leave the current route.

You can follow all the steps similar to the first example for this example.

app/templates/myroute.hbs

HTML




<form>
    <label>Name: <input type="text"></label>
    <label>Email: <input type="email"></label>
    <button {{action "willTransition" }}>Save</button>
</form>


app/router.js

Javascript




import Ember from 'ember';
import config from './config/environment';
  
const Router = Ember.Router.extend({
    location: config.locationType,
    rootURL: config.rootURL
});
  
Router.map(function () {
    this.route('myroute');
});
  
export default Router;


app/routes/myroute.js

Javascript




import Ember from 'ember';
  
export default Ember.Route.extend({
    actions: {
        willTransition(transition) {
            if (this.controller.get('isDirty')) {
let confirmation = confirm("Your changes haven't been saved. Are you sure you want to leave this page?");
                if (confirmation) {
                    // Save changes
                    this.controller.set('isDirty', false);
                } else {
                    transition.abort();
                }
            }
        }
    }
});


Output:

Output

Example 3: This is an example where we create an interface that uses transitionTo() method for routing from one route to another.

Javascript




import Route from '@ember/routing/route';
  
export default class IndexRoute extends Route {
    beforeModel() {
        this.transitionTo('home');
    }
}


Here, the application starts on the IndexRoute, which immediately redirects the user to the HomeRoute by simply calling the transitionTo() method.

Javascript




import Route from '@ember/routing/route';
  
export default class HomeRoute extends Route {
    model() {
        return {
            message: 'Welcome to GeeksforGeeks'
        }
    }
  
    actions: {
        goToAbout() {
            this.transitionTo('about'); 
        }
    }
}


In this part of the code, the HomeRoute has a model which returns an object this model has a single property as ‘message‘. The HomeRoute template then uses this model to display the message “Welcome to GeeksforGeeks” on the page. There is also a button this button, when clicked, triggers the goToAbout action that uses the transitionTo method to navigate the user from the current route to the “about” route.

HTML




<h1>{{model.message}}</h1>
<button {{action 'goToAbout'}}>Go to About</button>


Output:

Output

When the user clicks on the “Go to About” button, the goToAbout action is triggered and transitionTo(‘about’) is called. Due to this browser is forced to navigate to the “about” route and display the appropriate template.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads