Home >Web Front-end >JS Tutorial >Getting started with Ember and Ember CLI

Getting started with Ember and Ember CLI

William Shakespeare
William ShakespeareOriginal
2025-02-19 11:56:10747browse

Getting started with Ember and Ember CLI

Core points

  • Ember CLI is a command line tool built for Ember, which combines a variety of functions such as generator, compressor, CSS preprocessor compiler, automatic reloading and ES6 module loader. It can be used as an alternative to tools like Grunt and Gulp for setting up new Ember projects.
  • Ember follows the concept that conventions are better than configuration, which means it has many default settings that simplify the development process. Key elements include routing, controllers, templates, components, and Ember-Data.
  • This tutorial provides a step-by-step guide on how to build a simple contact manager application using the Ember CLI. It covers the capabilities of creating new Ember projects, setting fixed data, generating user models and routing, creating user templates, and adding display and editing user information.
  • Ember is a powerful JavaScript framework for building large web applications. With the Ember CLI, it provides a standardized development environment that makes it easier to manage dependencies, automate tasks, and execute best practices.

Ember has undergone many changes over the years. The biggest change is the introduction of Ember CLI, a command line tool built for Ember. It combines a variety of functions such as generator, compressor, CSS preprocessor compiler, automatic reloading and ES6 module loader. This command line tool will help you reduce the time you spend setting up tools like Grunt and Gulp. It's arguably a good alternative to these tools for any brand new Ember project. In this article, you will learn how to build a simple contact manager application using the Ember CLI. This tutorial is slightly different from other articles about Ember that I posted on SitePoint because they don't come with the Ember CLI. However, most of these concepts still apply, so I recommend you check them out and keep learning. The complete code for this article can be found on GitHub.

How to install Ember CLI

To install the Ember CLI, you need to install several dependencies first. The first one is Node.js. You need at least version 0.12.x. Next, you need to install Bower, which can be done by running the following command:

<code class="language-bash">npm install -g bower</code>

Then, to install the Ember CLI, run the following command:

<code class="language-bash">npm install -g ember-cli</code>

How to create a new Ember project

Before starting a wonderful operation, you need to open the terminal and execute the following commands in order to create a new project folder called contactmanager:

<code class="language-bash">ember new contactmanager</code>

Second step, go to the directory and install all npm and Bower dependencies using the following command:

<code class="language-bash">cd contactmanager
npm install
bower install</code>

At this time, start the built-in Ember server by executing the following command:

<code class="language-bash">ember serve</code>

You can now access your new application at URL localhost:4200. This is the default port for the Ember application running on the local computer, but you can change it as you like. If you follow all the steps instructed, you should now see a title in your browser that says "Welcome to Ember".

Ember Conventions and Structures

Before we dive into the application, let's review some of the Ember conventions.

Router and Router

Routing is the entry point for the Ember application. Router definitions are used in the app/router.js file. They allow you to access different parts of the application. For example, if you decide that you need to manage users in your application, you must define user routes. You can do this using the following syntax:

<code class="language-bash">npm install -g bower</code>

This will create the following URL for us:

  • /users/
  • /users/index/
  • /users/loading/

By convention, when you define a route, Ember expects to find other association types, such as routes, controllers, and templates. We can decide to create these types explicitly, or allow Ember to create them for us. In many applications, you will most likely have to create them yourself, but it's up to you. Remember, it is crucial to distinguish between routers and routes. The URL structure we created above is done using a router. These only show the intent we want to use these URLs in the application. We haven't created actual routes, but just URLs for those routes. To create a route we have to follow this process in the routes folder. If you are confused, don't worry, as I'll look at this topic more deeply later in this article.

Controller

Controller is a type used to store view state, located in the app/controllers folder. They work in conjunction with routing. In this case, the above URL corresponds to /user/ and requires a controller named /users/. Also here, we are free to choose whether to define it ourselves. The controller also defines event handlers for view operations (such as clicks, hovers, etc.).

Template

The template is the representation part of Ember. You write it in a template language called Handlebars, which compiles to pure HTML. The template is located in the app/templates folder.

Components

Components are small self-contained functional blocks. You can think of them as a combination of representations and features, they are reusable and easy to maintain.

Ember-Data

This is a library maintained by the Ember core team that complements the Ember core and acts as a front-end ORM for managing data models. There are other alternatives I haven't used before and are out of the scope of this article, as we'll be using Ember-data.

App

The contact management application we will build will include a list of users and their available contact information. The application will allow us to create, edit, delete and view users. To make our application concise and clear, we will use the fixed adapter that comes with the Ember CLI. This acts as a backend, except that the data is not persisted when the page is refreshed. First, if you haven't created it, use the ember new contactmanager to create a new Ember project.

Generate user model

Move to the project folder and generate the user model using the following command:

<code class="language-bash">npm install -g ember-cli</code>

This will create a file named user.js in app/models, with the following content:

<code class="language-bash">npm install -g bower</code>

Make the necessary changes so that the export statement looks like this:

<code class="language-bash">npm install -g ember-cli</code>

This defines the properties our user model will have.

Generate user route

Now, add the following lines to your router.js file to give us some available URLs:

<code class="language-bash">ember new contactmanager</code>

We have three new URLs. One is to list users, the other is to view individual users, and the last is to edit user information. Next, let's create a user route using the following command:

<code class="language-bash">cd contactmanager
npm install
bower install</code>

This route will be used to retrieve our user list. Change its content using the following code snippet:

<code class="language-bash">ember serve</code>

Set fixed data and generate user templates

At this point, let's add some temporary data to our application. To do this, run the following command:

<code class="language-javascript">Router.map(function() {
  this.resource('users', function() {});
});</code>

This will generate a file named application.js in the app/adapters/ folder. By default, Ember uses RestAdapter to query the model. This adapter assumes that you have a backend system that provides JSON data to your Ember client application. Since we don't have a backend, in this case we want to use fixed data instead. Therefore, we will update the adapter code as follows:

<code class="language-bash">ember generate model user</code>

and add the following to your user model to create some fixtures.

<code class="language-javascript">import DS from 'ember-data';

export default DS.Model.extend({
});</code>

If you navigate to URL localhost:4200/users, you will only see the old greeting messages, and not the user pinned data we just added. To view user data, we need to create a template for the user using the following command:

<code class="language-javascript">export default DS.Model.extend({
  firstName: DS.attr(),
  lastName: DS.attr(),
  addressLine: DS.attr(),
  postCode: DS.attr(),
  country: DS.attr()
});</code>

This creates a file named users.hbs in the app/templates/ folder. Open this file and update its contents as follows:

<code class="language-javascript">Router.map(function() {
  this.resource('users', function() {
    this.route('show',{path: '/:user_id'});
    this.route('edit',{path: '/:user_id/edit'});
  });
});</code>

You should now see a list of users, each with an edit text next to it. Because we only have one user in the fixed data, we will only see one user. You can add more user objects to the user fixture as needed. Just make sure each object has a unique ID.

Show individual users

Now that we have listed our users, let's see how to display the full information of the user. first. Change the code in the users template by enclosing the "edit" text next to each username with a link. Then, change "Edit" to:

<code class="language-bash">ember generate route users</code>

Next, let's generate a user controller using the following command:

<code class="language-javascript">import Ember from 'ember';

export default Ember.Route.extend({
  model: function(){
    return this.store.find('user');
  }
});</code>

Inside (user controller), change the content to the following:

<code class="language-bash">ember generate adapter application</code>

After finishing, use the following command to generate a template for editing the user:

<code class="language-javascript">import DS from 'ember-data';

export default DS.FixtureAdapter.extend({
});</code>

Currently, the created template (app/templates/users/show.hbs) is empty. Open it and add the following code:

<code class="language-javascript">User.reopenClass({
   FIXTURES: [{
      id: 1,
      firstName: 'James',
      lastName: 'Rice',
      addressLine: '66 Belvue Road',
      postCode: 'M235PS',
      country: 'United Kingdom'
   }]
});</code>

Do this and you should be able to see the full information for each user you click on.

Edit single user

If you want to edit a single user, you have to follow some simple steps. First, link to user edit routes by enclosing the "edit" text next to each username with a link. Then, change "Edit" to:

<code class="language-bash">npm install -g bower</code>

Next, let's generate a user controller using the following command:

<code class="language-bash">npm install -g ember-cli</code>

Inside (user controller), change the content to the following:

<code class="language-bash">ember new contactmanager</code>

After finishing, use the following command to generate a template for editing the user:

<code class="language-bash">cd contactmanager
npm install
bower install</code>

In the new template app/templates/users/edit, paste the following code:

<code class="language-bash">ember serve</code>

This code calls the saveUser() function on our controller when submitting the form. This function passes the user being edited and saves the modified information. With this change, you can edit the details of the user when you click on the edit link for the user. When you click the Save button, you can save them, after which you will be redirected back to the user list. Long live! We now have a simple contact list manager. You can convert it into a full application by connecting it to a real backend to persist data when the page refreshes. I also encourage you to add delete functionality to the app so that you can delete unwanted users at any time.

Conclusion

Emberhttps://www.php.cn/link/0e0f9e664029e8912996d65c1cf09761 is a framework for building large web applications. It has the idea that conventions are better than configuration, which means it is based on several common decisions and has many defaults (conventions), which makes your development process easier. This way, you don't have to make many trivial decisions during the development process. I hope you enjoyed reading this tutorial and learning new things about how to use such a powerful and simple JavaScript framework in your project. Please let us know what you think in the comments below. You can find the code for the application on GitHub.

Frequently Asked Questions about Getting Started with Ember and Ember CLI

What is the difference between Ember and Ember CLI?

Ember is a JavaScript framework for building web applications, and Ember CLI is a command line tool that helps you create, develop, and build Ember applications. Ember CLI provides a standardized development environment that makes it easier to manage dependencies, automate tasks, and execute best practices.

How to install Ember CLI?

To install Ember CLI, you need to install Node.js and npm on your system. After installing these prerequisites, you can install the Ember CLI using the following command in the terminal: npm install -g ember-cli.

I get an error message saying "You must be inside the Ember CLI project to use the serve command". What does this mean?

This error occurs when you try to run the ember serve command outside the Ember CLI project directory. To resolve this issue, use the ember serve command to navigate to the root directory of the project before running cd.

How to create a new Ember application using the Ember CLI?

You can use the ember new command followed by the name of the application to create a new Ember application. For example, ember new my-app will create a new Ember application called "my-app".

What basic Ember CLI commands should I know?

Some basic Ember CLI commands you should know include ember new (create a new application), ember serve (start a development server), ember generate (generate a new file), and ember build (build your application program for deployment).

How to build my application for production using Ember CLI?

You can use the ember build command and set the --environment option to "production" to build your application for production. The command looks like this: ember build --environment production.

How to generate new files in my Ember application using Ember CLI?

You can use the ember generate command followed by the file type and its name to generate a new file in the Ember application. For example, ember generate route about will generate a new route called "about".

How to start a development server using Ember CLI?

You can start the development server using the ember serve command. This will start the server and make your application accessible at http://localhost:4200.

How to update the Ember CLI?

You can use the command npm uninstall -g ember-cli to uninstall the old version and then use the command npm install -g ember-cli to install the new version to update the Ember CLI.

What is the purpose of the.ember-cli file?

.ember-cli File is the configuration file of the Ember CLI. It allows you to customize the behavior of your Ember CLI project. For example, you can specify the default port of the development server, enable or disable certain features, and more.

The above is the detailed content of Getting started with Ember and Ember CLI. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn