Light the Flame! Ember.js Beginner's Guide

Source: Internet
Author: User
Tags closing tag creative commons attribution list of attributes script tag unique id uppercase letter

Complex JavaScript applications can now be seen everywhere. As these applications become more complex, a long list of jQuery callback statements, or different function calls made through the application at various points, are no longer acceptable. This has led JavaScript developers to understand the problems that traditional software programmers have known for decades: Organization and efficiency are important and can have a significant impact on the performance of the application.

One of the most common architectural patterns for achieving organization and efficiency is known as the Model View Controller (abbreviated to MVC). This pattern encourages developers to split different parts of their applications into more manageable chunks. Instead of using a function to call the database directly, you can create a model to manage the database for you. You do not have to use an HTML file that is full of output and logic statements, and a simple template or view can simplify the display of your code. Finally, the controller (director) manages the flow of your application, helping a variety of fragmented parts communicate more efficiently with each other. Using this pattern in your application makes it easier to add new functionality.

As part of a recent outbreak of Internet-based software development, a bewildering array of MVC frameworks emerged, such as Ember.js, Backbone.js, Knockout.js, Spine.js, Batman.js, and Angular.js. On the one hand are beginner and mid-level developers, and the other is the Ashes programmer, which complements the gap between these libraries, written in JavaScript and designed for JavaScript development. They offer a wide range of features and capabilities to meet the needs of developers for different developers with varying skill levels.

In this tutorial, you'll be more familiar with ember.js by building an available Twitter Timeline viewer.

Ember.js Introduction

Ember.js is one of the newest members of the JavaScript framework package. It evolved the SproutCore project that was originally created in 2007 and is used extensively by Apple in a variety of Web applications, including MobileMe. The emberjs.com,ember is described as "a JavaScript framework for creating large Web applications that can eliminate boilerplate and provide a standard application architecture." "It itself tightly integrates the template engine named handlebars, which provides one of the most powerful features for Ember: Two-way data binding. Ember also provides additional features such as state management (where a user's state is logged off or logged in), an automatic Update template (your UI changes when the underlying data changes), and a computed attribute (firstName + lastName = fullName). After a year of reliable development, Ember has become a powerful player.

Ember has only one dependency-jquery. The boilerplate HTML settings for the Ember application should look similar to the following code. Please note that both JQuery and Ember are updated from the CDN (content delivery network). If users have already downloaded these files when they visit other sites that need them earlier, this will speed up the user's page load.

Defining MVC

It may be a good idea to define MVC more explicitly before you continue this tutorial. This concept has emerged in the 1979, and since then there have been a number of different variants of the model. The most common process is usually this:

    1. The user performs an action, such as tapping on the keyboard or clicking the mouse button.
    2. The controller receives input and triggers a message to the model.
    3. The model modifies its contents according to the message (deleting one row or updating the number of shopping carts).
    4. The view monitors changes in the model and updates the user interface accordingly.

Understanding how the MVC pattern works makes it easier for your applications to flow. In addition, because the code is split into different blocks, the developer team can work together more easily without interfering with each other.

Ember How to perform MVC

JavaScript is a flexible and powerful language, but it also has shortcomings. It does not provide the out-of-the-box functionality that makes it suitable for MVC style development. So Ember expanded the base language with a bunch of extra features. When building Ember applications, you will use four main parts: Application (Application), model (models), view (view), and controller (director). Each part is reviewed in the following sections.

Application (Application)

A ember.application instance is required for each Ember application. This is the basis for all the rest of the code, and it provides useful functionality, as well as namespaces (one way to group the rest of the application's parts). Defining a Ember application is simple:

Songs = Ember.Application.create({ mixmaster: ‘Andy‘ });

The code defines a named Songs application that sets the property named to mixmaster Andy . You can change the name of the application to any name you like, but Ember requires that the name of the variable begin with an uppercase letter so that the bound system can find it. You can also add additional built-in options when you create an application, and you can add any property or method, but the primary concern for novice users may be the ready() method. The method works document.ready() exactly like the jQuery block, and can be implemented in the following ways:

Songs = Ember.Application.create({ mixmaster: ‘Andy‘, totalReviews: 0, ready: function(){ alert(‘Ember sings helloooooooooo!‘); } }); Models (model)

If there is no data, the application is meaningless. Ember uses Models to help developers manage data in a structured way. In addition to saving data, Ember Models also models its internal data. In other words, if you want to store information about the MP3 collection, your model may contain a title property, an artist attribute, and a genre attribute. The model may look like the following:

Songs.Song = Ember.Object.extend({ title: null, artist: null, genre: null, listens: 0 });

There are a few things to keep in mind about these lines of code.

    • You will immediately see the namespace in use by your application. Songsis the name of the application, and the Song name of the model.
    • When you extend an object, you are creating blueprints for future instances of this model. Because this is the Lord because this is the main object, all songs will be based on it, so it uses an uppercase letter. These naming conventions make it easier for you to distinguish the types of objects you are using in the future.
    • When you create a model, you can provide a default value for each property. title, artist and genre attributes can be filled in later, so they are marked null (or None). The listens property defaults to 0 , and its value increases as you listen to the music collection.

Now that the Song model is in place, you can add the first song. You used extend to initialize the Song model, but you will use create it to add an instance of it. Here's what it looks like:

mySong = Song.create({ title: ‘Son of the Morning‘, artist: ‘Oh, Sleeper‘, genre: ‘Screamo‘ });

Note that the variable does not start with an uppercase letter, because it is Song an instance of the model. The new song is not Songs in the namespace either. You will almost no longer need to create instances of the model in your application. Of course you do, but in general you will place each instance of the model in a larger collection of similar objects, such as Arraycontroller, which is described in more detail later.

Views (view)

In an Ember application or any MVC-style application, view is a component that the user can see and interact with. You can define an inline template by adding the original HTML directly to the page. The template will be included in the script markup. You can add it to any location on the page where you want the content to appear.

<script type="text/x-handlebars"> Hello <b>{{Songs.mixmaster}}</b> </script>

Note that the script type of the tag is text/x-handlebars . This allows Ember to fetch something when the page is loaded. Ember automatically prepares any HTML contained within this script tag for use in your application. By stacking these lines in your application, the following text is displayed:

Hello <b>Andy</b>

Before you continue, take a closer look. In your browser, right-click the bold text and use the browser's developer tool to check it. You may have noticed some extra elements. In order to know which part of the html,handlebars is to be updated when a basic property changes, the markup element with a unique ID is inserted, for example:

<b> <script id="metamorph-0-start" type="text/x-placeholder"></script> Andy <script id="metamorph-0-end" type="text/x-placeholder"></script> </b>

You can define a view directly in JavaScript, and then use the view helper to display it to the page. Ember has a common view that allows you to create simple markup in your application div , but it also comes with a prepackaged set of views that you can use to build basic controls such as text entry boxes, check boxes, and selection lists. Start by defining a simple view in a JavaScript file TextArea .

Songs.ReviewTextArea = Ember.TextArea.extend({ placeholder: ‘Enter your review‘ });

It is then displayed to the page by referring to the view path that starts with the variable that contains the view, beginning with the word. Run the following code to display the TextArea field in your browser with the placeholder text "Enter your review". You can also specify rows and cols act as additional attributes in the definition.

<script type="text/x-handlebars"> {{view Songs.ReviewTextArea}} </script> Handlebars

Now, you might want to know what's in the code {{ and }} What it means, and we can just talk about handlebars, also known as mustaches. Think about it a little bit and you'll see why they're called handlebars pard ' ner. Handlebars is a template engine that allows developers to mix raw HTML and handlebars expressions to produce rendered HTML. Expression to {{ start, and to }} end. As mentioned earlier, all templates must be placed text/x-handlebars inside a tag of type script .

By default, any value contained within handlebars is allegedly bound to its value. This means that if the value changes due to some other action within the application, the value displayed to the user will also be updated. Consider the following code:

<script type="text/x-handlebars"> My songs have {{Songs.totalReviews}} reviews. </script>

The first time you initialize your application, the user will see the following text.

My songs have 0 reviews.

However, with data binding, Songs.totalReviews this value changes in real time as more comments are added as a result of the update.

Handlebars also {{#if}} {{else}} supports flow control by using and. These elements enable you to conditionally implement a template based on values in your application. You can modify the previous example to display another message to the user when there is no comment:

<script type="text/x-handlebars"> {{#if Songs.totalReviews}} Read all my reviews! {{else}} There are no reviews right now. {{/if}} </script>

If the value changes at any point in the application's life cycle, Songs.totalReviews the view updates and displays another part of the message. It is worth noting that, # and the / symbol is just to tell handlebars that this particular view helper has a closing tag.

Controllers (Controller)

Previously, model was defined as a way to enable developers to manage data. That's true, but it's a narrow definition. A model contains only data related to a single thing; for example, a song (but not many songs) or a person (but not multiple people). When you want to manage multiple data blocks of the same type, you need a controller. With Ember, you can use Arraycontroller to manage multiple sets of songs, people, parts, or anything. Each arraycontroller has built-in content properties for storing data. The data can be a simple string or a complex value, such as an array or an object. In addition, the functions contained in Arraycontroller can be used to interact with the data contained in the Arraycontroller. What does the Arraycontroller of your Song collection look like?

Songs.songsController = Ember.ArrayController.create({ content: [], init: function(){ // create an instance of the Song model var song = Songs.Song.create({ title: ‘Son of the Morning‘, artist: ‘Oh, Sleeper‘, genre: ‘Screamo‘ }); this.pushObject(song); } });

initThe function is not required, but it is convenient because the songsController function is triggered once it is ready init . It can be used to populate existing data into a controller, in this case, you will use it to add a song to the controller to demonstrate Ember data binding. Add the previous Arraycontroller definition and the following inline template, and run the code in your browser:

<script type="text/x-handlebars"> {{#each Songs.songsController}}

The Handlebars each helper receives a path to a set of data and then loops it. Everything in each block that matches each item in the controller is each displayed on the page. Note that you do not provide direct access to the array of contents, because, for Ember, the controller is an array. The resulting HTML output is as follows:

Full integration: Embertweets

At this point, you should have a better understanding of what Ember is and what it can do. You should also understand each component that enables Ember to implement its capabilities: application (application), model (models), view (view), and controller (director). Now it's time to apply this knowledge to write a truly usable application. You'll skip the industry-standard "Todo app" and move on to being closer and familiar to many people: Twitter. In the remainder of this tutorial, you will build a Twitter timeline viewer. It may be helpful to look at the final results before writing any code.

To create a template file

Using the boilerplate HTML page at the beginning of this article, you will first build the underlying HTML. Copy the following code and paste it into a new HTML file named Index.html. You need to reference the CSS file in the sample file in this article. The sample file also contains a starting point for the project and can be used at any time.

<!doctype html>

You can see that the app has three parts: an input field that allows the user to enter a Twitter user name, a timeline viewer to display tweets for the selected Twitter user, and the latest list of users that will store the previous search.

The search box will appear at the top of the page, the newest user in the left column, and the tweet itself will occupy most of the pages on the right side of the page.

Next, create another file named App.js, and add the following. These annotations can help you keep your code organized. Load this page in your browser and make sure there are no errors.

/************************** * Application **************************/ /************************** * Models **************************/ /************************** * Views **************************/ /************************** * Controllers **************************/ Application initialization

The first thing you need to do is to initialize your application. Directly below the comment block labeled application, put the following code:

App = Em.Application.create();

Note that this line is not using ember.application, but em.application. You can use "Ember" anywhere you might want to use "Em", and the Ember team reduces the number of words to enter by adding this handy shortcut.

Next, you will add the TextInput view and the Submit button. Directly below the comment block labeled "views," put the following code:

App.SearchTextField = Em.TextField.extend({ insertNewline: function(){ App.tweetsController.loadTweets(); } });

This block starts with the APP namespace and then expands one of the pre-packaged view TextField for Ember. In addition to allowing arbitrary properties and functions within the views, Ember also provides built-in helper functions. That is the function, which is executed whenever the cursor is in the insertNewLine() input box and the user presses the Enter/return key on the keyboard.

Create a template block

Now that you have defined the TextField view, you will add the appropriate view helper code to the HTML file. Switch to index.html and add the following code directly after the line that appears as "Load Tweets for". Keep in mind {{ that }} any and all of the code inside is a template and will be Ember for output data. In addition, any template that starts with a word refers to a view view that has already been defined in your JavaScript code.

{{view App.SearchTextField placeholder="Twitter username" valueBinding="App.tweetsController.username"}} <button {{action "loadTweets" target="App.tweetsController"}}>Go!</button>

This section of the template contains a view helper, and a {{action}} button tag with an auxiliary program. TextField View SearchTextField begins with placeholder text, which is a property built into the HTML5 text input field. If the field is blank, the placeholder text in the attribute is placed in the input field. When someone starts typing, the value disappears. Ember enables developers to use any of the HTML 5 standard properties within their built-in views.

The second property highlights the ability to Ember data binding. Ember uses a set of conventions to help it determine what you want to accomplish. Any property in the view (a template or a view in a JavaScript file) that ends with the word "Binding" (note capital letter) automatically sets the binding for the property that precedes it. In this example, Ember App.tweetsController.username binds the value to the property of the input field value . Whenever the contents of a variable change, the value in the input field is automatically updated and vice versa.

{{action}}Makes it easier to add functionality to input-driven elements. It has two options: operation name and Target. The two combine to form a "path" that points to the functions contained in the Ember object. In the example of the above button, the path will be the App.tweetsController.loadTweets() same function that is called when the user presses the Enter key within the text field. Load index.html in your browser and click the Submit button, or press Enter in the input field. If you view the browser console, you will see an error. This is because there is no definition yet App.tweetsController .

Preparing Tweet Storage Objects

Now is a App.tweetsController good time to define. ControllersAdd the following code after the comment block in App.js. You should already be familiar with the following code. namespaces, Arraycontroller, content arrays-everything is in. But this time you will add an arbitrary attribute ( username ) and a function ( loadTweets ). After adding Arraycontroller, reload your browser. Enter a word in the input box, and then click the button. You will get a prompt box to echo the words you typed. You can delete the prompt line at any time. You will also see an error indicating that the method has not been defined addUser .

App.tweetsController = Em.ArrayController.create({ content: [], username: ‘‘, loadTweets: function() { var me = this; var username = me.get("username"); alert(username); if ( username ) { var url = ‘http://api.twitter.com/1/statuses/user_timeline.json‘ url += ‘?screen_name=%@&callback=?‘.fmt(me.get("username")); // push username to recent user array App.recentUsersController.addUser(username); } } });

Take a closer look at loadTweets the definition of the function; it has some strange code. The remainder of the first behavior function sets a range . By definition, the scope or this is the current function for all Ember objects, in this case App.tweetsController . However, in this tutorial, you can add more features to a function later loadTweets . Setting the current scope now helps Ember understand the context you're using.

As mentioned earlier, Ember provides many helper functions that make it easier to write applications that include get() and set() . The two functions are built into each Ember object and provide quick access to any property or function. The next line uses the scope of the current object, App.tweetsController and then calls the get() function to pass in the name of the property whose value you want to get. You may wonder where the value of the user name to use at the beginning comes from. Keep in mind that Ember data binding is bidirectional. This means that once you type a value in the input field, the property of the input field view valueBinding updates the object with a value App.tweetsController .

After the user name is retrieved, a test is run to ensure that it is not empty. ifThere are only two statements in this block, but this will change later. The first statement sets the URL for a user to a JSON file for Twitter. You may not notice what's special here, but take a closer look and you'll find the sum at the end %@ .fmt() . .fmt()The function performs a convenient string substitution, which is used %@ as a token. Because the design of your application requires that you store a search list, you must store your search terms in some way. The last line executes the function, pushing the value of the user name to App.recentUsersController Arraycontroller. Because the object does not already exist, running the code produces an error.

Search before storing

In the following section, you will create an object to store the most recent search. Use the following code and add it App.tweetsController behind the object.

App.recentUsersController = Em.ArrayController.create({ content: [], addUser: function(name) { if ( this.contains(name) ) this.removeObject(name); this.pushObject(name); }, removeUser: function(view){ this.removeObject(view.context); }, searchAgain: function(view){ App.tweetsController.set(‘username‘, view.context); App.tweetsController.loadTweets(); }, reverse: function(){ return this.toArray().reverse(); }.property(‘@each‘) });

You are already familiar with how to create Arraycontroller and add an empty array of content, but the object has some new elements that addUser begin with a function. This will use contains() the built-in Ember function named to examine the existing array ( this ). If it finds a result, it uses the Arraycontroller function to removeObject() delete the result. In contrast to this function, there is a pushObject() function called, which is used to add a separate object to the content array. Both of these functions have complex versions that handle multiple objects: pushObjects() and removeObjects() . This code deletes the existing search term before adding the search term, so the same search term is not displayed more than once. Now that you know how to remove an object from the content array, the removeUser() only new element in the function is the parameter. When {{action}} a function is called using a helper program, Ember implicitly passes a reference to the current view. In App.tweetsController The example, the view has a context, which is basically the item that is currently being traversed. The context is used to remove the selected item from the array.

searchAgain()The function also receives the current view as a parameter. When the user clicks a previously searched word, the function populates with the selected user name App.tweetsController.username and then triggers the loadTweets() function to provide a click view for the previous search.

By default, Ember displays content to the page in ascending order. Array index 1 is the first, array index 2 is the second, and so on. The design of this application requires that the most recent search be displayed in descending order. This means that the array must be reversed. Although this is not a built-in function, you can see how easy it is to add it. Reverse()First Use the Ember toArray() function to convert the Ember content array into a normal array, reverse it, and then return it. So that the function can be used as a data source, is the function added at the end property() . The property() function uses a comma-delimited list of attributes required by a specified function. In this case, the property() function implicitly uses the content array itself, using @each a dependent key to address each element within the array. In the next section, you'll see how to implement the reverse() function.

Show previous searches

Now that you have stored the previous search, it is time to display them on the page. Copy the following template and add it after the tag labeled Recent Users h3 .

<ol> {{#each App.recentUsersController.reverse}} <li> <a href="#" title="view again" {{action "searchAgain" target="App.recentUsersController"}}>{{this}}</a> - <a href="#" title="remove" {{action "removeUser" target="App.recentUsersController"}}>X</a> </li> {{/each}} </ol>

You should now be familiar with all of this code. The each block points to the content array, and the HTML contained within it is applied to App.recentUsersController each item in the variable. You do not have to explicitly point to the content array, but in this case, the code points to the reverse function, which provides the data in reverse order. {{action}}the helper program lets the user click each anchor tag and trigger the specified function. The only element that may not be familiar is {{this}} . When iterating through an array of contents, Ember {{this}} holds a reference to the current index in the variable. Because the value of each item is just a string, you can use {{this}} the direct output value of the current item. Clicking the Twitter user name will reload the user's tweets, and clicking on the tweets will recentUsersController remove them from them.

Loading tweets

It's okay to save the search term, but what about actually performing the search? Next, you'll add a fragment that retrieves the JSON package from Twitter and displays it to the page. Use the following Ember Model and add it directly behind the comment block labeled model. Keep in mind that the Ember Model is the data they will contain is a blueprint.

App.Tweet = Em.Object.extend({ avatar: null, screen_name: null, text: null, date: null });

In App.js, locate App.recentUsersController.addUser(username); the line of code that is displayed, and add the following code directly after it:

$.getJSON(url,function(data){ me.set(‘content‘, []); $(data).each(function(index,value){ var t = App.Tweet.create({ avatar: value.user.profile_image_url, screen_name: value.user.screen_name, text: value.text, date: value.created_at }); me.pushObject(t); }) });

If you've used JQuery before, you might have used a .get() function to retrieve the data. The .getJSON() function does the same thing, but it sees the JSON package as a result. In addition, it uses the returned JSON string and transforms it into an executable JavaScript code. After the data is retrieved, the content array is emptied and all existing tweets are deleted. The next line extracts the packet and encapsulates it in a JQuery object, so .each() the method can loop the generated Tweets. In the each block, a copy of the Tweet Model is populated with data and then pushed to Arraycontroller.

Finally, you need to add the following display code to index.html. Copy and paste it directly Tweets behind the tag tag h3 .

<ul> {{#each App.tweetsController}} <li> <span>{{date}}</span>

Ember uses pure {{Handlebars}} can easily output data to the page, but there is a problem. Remember how Ember wrapped the output value in a script tag? This is not an option when you are using HTML attributes. So Ember provides the {{bindAttr}} auxiliary program. Any properties placed within this helper will be output as usual, but the bindings remain. Continue with the operation and now run your application. Enter a user name and you will see Tweets appear.

Next reading direction

In this article, you learned the basics of ember.js functionality. You also learned how Ember uses its models, views, Controllers, and, of course, application objects to implement MVC. You use handlebars to create a template from a view helper and an action helper program. You learned how to use Models to create a blueprint for your data, use Controllers to store the data in a collection set, and use views to display the data to the page. Finally, you used Ember to build a complete application with data binding, computed properties, and Automatic Update templates. Your mother will be very proud of you!

For more reading about Ember, check out some of the links below:

    • Ember.js
    • Ember.js Documentation
    • The Emberist
    • Tom Dale at the Ember.js Meetup
    • Andy Matthews Blog
    • Cerebris Blog
    • Code 418 Holy Moly Blog


This article was published based on the creative Commons attribution-noncommercial-share Alike 3.0 Unported License protocol.

Light the Flame! Ember.js Beginner's Guide

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.