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:
npm install -g bower
Then, to install the Ember CLI, run the following command:
npm install -g ember-cli
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:
ember new contactmanager
Second step, go to the directory and install all npm and Bower dependencies using the following command:
cd contactmanager npm install bower install
At this time, start the built-in Ember server by executing the following command:
ember serve
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:
npm install -g bower
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:
npm install -g ember-cli
This will create a file named user.js in app/models, with the following content:
npm install -g bower
Make the necessary changes so that the export statement looks like this:
npm install -g ember-cli
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:
ember new contactmanager
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:
cd contactmanager npm install bower install
This route will be used to retrieve our user list. Change its content using the following code snippet:
ember serve
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:
Router.map(function() { this.resource('users', function() {}); });
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:
ember generate model user
and add the following to your user model to create some fixtures.
import DS from 'ember-data'; export default DS.Model.extend({ });
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:
export default DS.Model.extend({ firstName: DS.attr(), lastName: DS.attr(), addressLine: DS.attr(), postCode: DS.attr(), country: DS.attr() });
This creates a file named users.hbs in the app/templates/ folder. Open this file and update its contents as follows:
Router.map(function() { this.resource('users', function() { this.route('show',{path: '/:user_id'}); this.route('edit',{path: '/:user_id/edit'}); }); });
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:
ember generate route users
Next, let's generate a user controller using the following command:
import Ember from 'ember'; export default Ember.Route.extend({ model: function(){ return this.store.find('user'); } });
Inside (user controller), change the content to the following:
ember generate adapter application
After finishing, use the following command to generate a template for editing the user:
import DS from 'ember-data'; export default DS.FixtureAdapter.extend({ });
Currently, the created template (app/templates/users/show.hbs) is empty. Open it and add the following code:
User.reopenClass({ FIXTURES: [{ id: 1, firstName: 'James', lastName: 'Rice', addressLine: '66 Belvue Road', postCode: 'M235PS', country: 'United Kingdom' }] });
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:
npm install -g bower
Next, let's generate a user controller using the following command:
npm install -g ember-cli
Inside (user controller), change the content to the following:
ember new contactmanager
After finishing, use the following command to generate a template for editing the user:
cd contactmanager npm install bower install
In the new template app/templates/users/edit, paste the following code:
ember serve
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
Emberhttp://ipnx.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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

Which JavaScript framework is the best choice? The answer is to choose the most suitable one according to your needs. 1.React is flexible and free, suitable for medium and large projects that require high customization and team architecture capabilities; 2. Angular provides complete solutions, suitable for enterprise-level applications and long-term maintenance; 3. Vue is easy to use, suitable for small and medium-sized projects or rapid development. In addition, whether there is an existing technology stack, team size, project life cycle and whether SSR is needed are also important factors in choosing a framework. In short, there is no absolutely the best framework, the best choice is the one that suits your needs.

IIFE (ImmediatelyInvokedFunctionExpression) is a function expression executed immediately after definition, used to isolate variables and avoid contaminating global scope. It is called by wrapping the function in parentheses to make it an expression and a pair of brackets immediately followed by it, such as (function(){/code/})();. Its core uses include: 1. Avoid variable conflicts and prevent duplication of naming between multiple scripts; 2. Create a private scope to make the internal variables invisible; 3. Modular code to facilitate initialization without exposing too many variables. Common writing methods include versions passed with parameters and versions of ES6 arrow function, but note that expressions and ties must be used.

Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)

CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.
