Explore Emberjs to create a simple Todo Application

Source: Internet
Author: User

Target
Emberjs is used to create a simple Todo application to achieve the following effect: Input text in the text box and create an event handler. You can select a priority for the event handler and delete the completed event.

Preparation
To complete this application, you need to prepare:
1. Create an html page, regardless of the style;
2. Script: emberjs, handlebars, and jQuery. These three scripts can be obtained from the Internet. We will add them to the head tag.

Production
Create a page and add a script to create an application. The html code is as follows:

Copy codeThe Code is as follows: <! Doctype html>
<Html>
<Head>
<Meta charset = "UTF-8">
<Title> Ember -- first application </title>
<Script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"> </script>
<Script type = "text/javascript" src = "http://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.rc.1.js"> </script>
<Script type = "text/javascript" src = "http://cloud.github.com/downloads/emberjs/ember.js/ember-1.0.0-pre.2.min.js"> </script>
</Head>
<Body>
</Body>
</Html>

According to the requirements of ember, you need to use Ember. Application. create () to create an Application instance first, which is also used as the namespace of the Application. This create method can pass an object attribute ready, which is a function called when the application is ready. Ember can also be replaced by Em.

Ember has an Em. Logger object, which is equivalent to window. console and can be used for debugging. We can add a message to this ready and display it in the console.

Now, add a script label to the head label to write the script of the application, instantiate an ember application, and add the area of each MVC module. The script code is as follows:

Copy codeThe Code is as follows :/********************
Application
********************/

Window. App = Ember. Application. create (
{
Ready: function (){
Em.Logger.info ('Welcome to the backlog application ');
}
}
);

/********************
Model
********************/

/********************
View
********************/

/********************
Controlle
********************/

Then, we need an input box to enter the agent items. We need to create an ember text box view. The ember View can be created using the Ember. View class (using the create method) or extended (using the extend method) A New View class. However, for the text box view, ember provides a more direct method-the Ember. TextField class. We can use this class to expand a custom view and then instantiate it and add it to the page. We name this text box View class AddItemView.

Add the text box view code in the view area of the script code:

Copy codeThe Code is as follows: App. AddItemView = Ember. TextField. extend ({

});

You can add a prompt to it. html5 supports placeholder and can be used. You also need to add the content to the list of representative items when you press Enter. here you need to use an attribute: insertNewline, which will call the corresponding function when you press Enter. The added code is as follows:

Copy codeThe Code is as follows: App. AddItemView = Ember. TextField. extend ({
Placeholder: 'enter To-Do List ',
InsertNewline: function (){}
});

Since you have not yet determined how to add the function, do not write it for the moment.

When you press enter, you need to add a list of items to be displayed. You can create a CollectionView In the ember to store the list project view. For CollectionView, by default, a content attribute is used to store list project objects. Its attribute value is an array. To display the list as ul list, you need to define the label name (tagName) of CollectionView as "ul ". We name this list view ListView and add it to the bottom of the text box view. The final code is as follows:

Copy codeThe Code is as follows: App. ListView = Ember. CollectionView. extend ({
Content: [],
TagName: 'ul'
});

If you open the page, NO content is displayed. Because the view has not been rendered, you need the support of the handlebar template to display the view.

Now let's modify the body block of the html page and add the two newly created views to see the effect.

The method for adding a handlebar template is <script type = "text/x-handlebars">/* view assistant */</script>. You can also specify the Template Name, defined in the data-template-name attribute, which will be used when a list project is added.

In the template, you need to add a view through the view Assistant (helper). The syntax is also very simple. Use two curly braces to enclose the view. The template keyword is used to specify the view to be displayed, for example: {view App. addItemView }}. You can find other template assistants on the handlebar Website: http://handlebarsjs.com /.

Add the text box and List View to the page. The modified body code is as follows:

Copy codeThe Code is as follows: <body>
<Script type = "text/x-handlebars">
<Span> enter the to-do list: </span >{{ view App. AddItemView }}< br/>

{View App. ListView }}
</Script>
</Body>

Refresh the page now and a text box is displayed, "Enter your agent items". The list is not displayed because there is no content.

At this time, we can add some content in the content, such as content: ['A', 'B', 'C'], and then refresh the page, you will find that the List area has only three small black spots (if you do not reset the list style ). Because you have added three items in content, but the list item has not specified a display template, the display is empty. To let you see the effect, Let's define a display template for the list items. Here we need to deal with two places. The first is to add the template with the specified name on the page, and the second is to define the attribute of the list project in the List View.

To define a list project, you need to use itemViewClass. It will pass each content item and display it with the specified template. Modify the List View ListView first and add the itemViewClass attribute to it. This is also a view, so you need to use Ember. view to create a template. When creating a template, specify the Template Name to be displayed as itemTemplate. This name will also appear in the handlebar Template Name of html. The modified code is as follows:

Copy codeThe Code is as follows: App. ListView = Ember. CollectionView. extend ({
Content: ['A', 'B', 'C'],
TagName: 'ul ',
ItemViewClass: Ember. View. extend ({
TemplateName: 'itemtemplate ',
})
});

Now we have modified the html. We need to create another handlebar template in the body and use the Template Name given above. The Code is as follows:

Copy codeThe Code is as follows: <script type = "text/x-handlebars" data-template-name = "itemTemplate">

</Script>

Next, add a template assistant. To pass each content item to the assistant, view. content is used. Add the following code:

Copy codeThe Code is as follows: <script type = "text/x-handlebars" data-template-name = "itemTemplate">
{View. content }}
</Script>

After that, refresh the page and display the content in the content. In addition, the li tag is automatically added to the template.

Continue to improve our applications. We can't always write the content as fixed, so how can users add it. Therefore, we want to save the project you want to add to an array, and then the content will retrieve the content of this array. At the same time, the ember framework supports two-way binding. When the array content is modified, the bound content also changes, and vice versa. Now, create an ember array and bind it to the content.

The ember array can be created through the ArrayController class. It will convert the common javascript that you pass into a new ember array object. we name the array used for project management as todoStore, in the controller Area of the html page, the created code is as follows:

Copy codeThe Code is as follows: App. todoStore = Ember. ArrayController. create ({
Content: []
});

Now you can put the content array in ListView into the todoStore array and bind the content array in ListView to todoStore. The two objects will be changed to the following:

Copy codeThe Code is as follows: App. ListView = Ember. CollectionView. extend ({
ContentBinding: 'app. todostore ',
TagName: 'ul ',
ItemViewClass: Ember. View. extend ({
TemplateName: 'itemtemplate'
})
});

/********************
Controlle
********************/
App. todoStore = Ember. ArrayController. create ({
Content: ['A', 'B', 'C']
});

Binding is a suffix that indicates Binding. The property value is the bound object. By default, the content attribute of the object is used. After the modification, refresh the page. If the page you see is the same as that before the modification, the modification is successful. Next, it is time to remove the value in content. The data we need will be input by the user in the text box.

Considering the current interaction process, the user enters the content in the text box, press enter, the program gets the event, calls a method to create a new object, and then sends the new object to todoStore, because of the binding function, an item is automatically added to the List.

It's time to modify the text box view. Do you still remember insertNewline? We can create a new project here. We will use three methods: set () Setting attribute values, get () Getting attribute values, pushObject () adding data. The code after modifying AddItemView is as follows:

Copy codeThe Code is as follows: App. AddItemView = Ember. TextField. extend ({
Placeholder: 'enter To-Do List ',
InsertNewline: function (){
Var item = this. get ('value ');
App. todoStore. pushObject (item );
This. set ('value ','');
}
});

Refresh the page, enter the content, and press Enter. The input content will be added to the list, indicating that the modification is successful. If you have not cleared the content in the content attribute of todoStore, there are now four list items.

We still have half of our goals. We still lack two features: select the priority and delete the completed project.

To add a drop-down list, you can use another convenient view: Ember. Select. You can directly create one in the template and bind the content in the drop-down list view to another ember object, and set the default priority. Priority also needs to be bound, so that the content in the corresponding ember object will be modified at the same time when the page is selected. First, create the ember object, and customize the selected Attribute of the object to indicate the selected value. Other names are also supported. This code will be added to the todoStore object and named selectController. The Code is as follows:

Copy codeThe Code is as follows: App. selectController = Ember. Object. create ({
Selected: 'low ',
Content: ['high', 'zhong', 'low']
});

Then add a template assistant and bind the corresponding attributes in selectController. selectionBinding is required for binding the selected items. By the way, a text prompt is provided and added to the text box template, the modified code is as follows:

Copy codeThe Code is as follows: <script type = "text/x-handlebars">
<Span> enter the to-do list: </span >{{ view App. AddItemView }}< br/>
<Span> Select priority: </span> {view Ember. Select contentBinding = "App. selectController. content" selectionBinding = "App. selectController. selected "}}
{View App. ListView }}
</Script>

Now, the drop-down list is displayed when you refresh the page.

It takes some time to make this priority appear for the list items. It's time to use model. Let's create a model class. When press enter, create an instance from this class and then throw the instance to todoStore. In addition, the template should also be modified, and the Creation Method of the text box view should also be changed. This change is a little more. In addition, a function for calculating attributes is also used, which is automatically updated when the dependent attributes change. Name this model TodoModel and place it in the model area. The Code is as follows:

Copy codeThe Code is as follows :/********************
Model
********************/

App. TodoModel = Em. Object. extend ({
Status :'',
Value :'',
Title: function (){
Return '[' + this. get ('status') + ']' + this. get ('value ');
}. Property ('status', 'value ')
});

Status indicates the selected priority, value indicates the value in the text box, and title indicates the content to be displayed in the list items. These attribute names are all custom. The title is not required because it is set as a computing attribute and depends on the status and value attributes. The property () method is the method for converting the ember function into a computing attribute, the following parameter indicates the attribute of the title dependency. When the status or value changes, it is automatically given.

Next, modify the insertNewline attribute of AddItemView. You need to obtain two data items: the content in the text box and the project selected in the drop-down list. How can I obtain the value of the text box? What is the value of the drop-down list? Don't forget that we have bound the selected item to the selected Attribute in selectController. You can just retrieve it from there. The modified AddItemView code is as follows:

Copy codeThe Code is as follows: App. AddItemView = Ember. TextField. extend ({
Placeholder: 'enter To-Do List ',
ElementId: 'add ',
InsertNewline: function (){
Var item = App. TodoModel. create ({
Status: App. selectController. get ('selected '),
Value: this. get ('value ')
});
App. todoStore. pushObject (item );
This. set ('value ','');
}
});

Now you can use the TodoModel class to instantiate a to-do project and add it to todoStore. Finally, you can modify the itemTemplate of the project list to display it, in the template, You need to obtain the title value of the current project for display. The Code is as follows:

Copy codeThe Code is as follows: <script type = "text/x-handlebars" data-template-name = "itemTemplate">
{View. content. title }}
</Script>

The new to-do list that is added now displays the priority.

Okay. Delete the last feature. Unlike adding pushObject, removeObject is used for deletion. Because it is displayed in each list item, you need to modify the itemViewClass and itemTemplate templates. we add a method in itemViewClass and call it when you click, name the method removeItem. The Code is as follows:

Copy codeThe Code is as follows: App. ListView = Ember. CollectionView. extend ({
ContentBinding: 'app. todostore ',
TagName: 'ul ',
ItemViewClass: Ember. View. extend ({
TemplateName: 'itemtemplate ',
RemoveItem: function () {this. getPath ('contentview. content'). removeObject (this. get ('content '));}
})
});

The last step is to add a link to the itemTemplate to accept clicks. The action assistant is used. The first parameter is the method name, and the target attribute is used to specify the object, call the method under the specified object when you click. The modified itemTemplate code is as follows:

Copy codeThe Code is as follows: <script type = "text/x-handlebars" data-template-name = "itemTemplate">
{View. content. title }}< a href = "#" {action removeItem target = "this" }}> X </a>
</Script>

Now the newly added project will have a cross on the right side. When you click it, the current project will be deleted.

Finally, you can make some improvements. The delete link is displayed only when you move the mouse over the project. To complete this function, you need to modify the itemViewClass and add the logical judgment assistant {# if} to the template }}. You can try it on your own, or you can look at the final complete code.

Copy codeThe code is as follows: full code
<! Doctype html>
<Html>
<Head>
<Meta charset = "UTF-8">
<Title> Ember -- first application </title>
<Script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"> </script>
<Script type = "text/javascript" src = "http://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.rc.1.js"> </script>
<Script type = "text/javascript" src = "http://cloud.github.com/downloads/emberjs/ember.js/ember-1.0.0-pre.2.min.js"> </script>
<Script>

/********************
Application
********************/

Window. App = Ember. Application. create (
{
Ready: function (){
Em.Logger.info ('Welcome to the backlog application ');
}
}
);

/********************
Model
********************/

App. TodoModel = Em. Object. extend ({
Status :'',
Value :'',
Title: function (){
Return '[' + this. get ('status') + ']' + this. get ('value ');
}. Property ('status', 'value ')
});

/********************
View
********************/
App. AddItemView = Ember. TextField. extend ({
Placeholder: 'enter To-Do List ',
ElementId: 'add ',
InsertNewline: function (){
Var item = App. TodoModel. create ({
Status: App. selectController. get ('selected '),
Value: this. get ('value ')
});
App. todoStore. pushObject (item );
This. set ('value ','');
}
});

App. ListView = Ember. CollectionView. extend ({
ContentBinding: 'app. todostore ',
TagName: 'ul ',
ItemViewClass: Ember. View. extend ({
TemplateName: 'itemtemplate ',
RemoveItem: function () {this. getPath ('contentview. content'). removeObject (this. get ('content '));},
MouseEnter: function () {this. set ('hover ', true );},
MouseLeave: function () {this. set ('hover ', false );}
})
});

/********************
Controlle
********************/
App. todoStore = Ember. ArrayController. create ({
Content: []
});

App. selectController = Ember. Object. create ({
Selected: 'low ',
Content: ['high', 'zhong', 'low']
});

</Script>
</Head>
<Body>
<Script type = "text/x-handlebars">
<Span> enter the to-do list: </span >{{ view App. AddItemView }}< br/>
<Span> Select priority: </span> {view Ember. Select contentBinding = "App. selectController. content"
SelectionBinding = "App. selectController. selected "}}
{View App. ListView }}
</Script>
<Script type = "text/x-handlebars" data-template-name = "itemTemplate">
{View. content. title }}{{# if view. hover }}< a href = "#" {action removeItem target = "this" }}> X </a >{{/if }}
</Script>
</Body>
</Html>

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.