SoFunction
Updated on 2025-04-05

Explore Emberjs to make a simple Todo app

Target
Use Emberjs to create a simple Todo application to achieve such an effect: by entering text in the text box, creating an agency item, which can select priority for the agency item and delete completed items.

Prepare
To complete this application, some preparations are required:
1. Create an html page, regardless of the style for the time being;
2. Scripts: emberjs, handlebars, jQuery. These three scripts are available online and we will add them to the head tag.

Production
Create a page, add a script, and you can start making the application. The html code is as follows:

Copy the codeThe code is as follows:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Ember--first application</title>
<script type="text/javascript" src="/ajax/libs/jquery/1.7.2/"></script>
<script type="text/javascript" src="/downloads/wycats//handlebars-1.."></script>
<script type="text/javascript" src="/downloads/emberjs//ember-1.0.0-pre."></script>
</head>
<body>
</body>
</html>


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

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

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

Copy the codeThe code is as follows:

/********************
application
********************/

= (
{
ready:function(){
('Welcome to do app');
}
}
);

/********************
model
********************/



/********************
view
********************/


/********************
controlle
********************/


Then we need an input box to enter the agent and we need to create an ember text box view. The ember view can be created (using create method) or extended (using extend method) a new view class. However, for text box view, ember provides a more direct way - class, we can use this class to extend a custom view first, and then instantiate it to the page. We name this textbox view class AddItemView .

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

Copy the codeThe code is as follows:

= ({

});


You can add a prompt to it. HTML5 supports placeholder and can be used. You also need to add the content to the representative matter list when pressing Enter. Here you need to use a property: insertNewline. The corresponding function will be called when pressing Enter. The added code is as follows:

Copy the codeThe code is as follows:

= ({
placeholder: 'Enter to do',
insertNewline:function(){}
});


Since the specific addition method has not been determined yet, the function body will not be written for the time being.

When the user presses Enter, a list is needed to display it. In ember, you can create a CollectionView to store the list item view. For CollectionView, by default there will be a content attribute to store the list item object, and its attribute value is an array. In order to make its list appear as an ul list, you need to define the tag name (tagName) of the 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 the codeThe code is as follows:

= ({
content:[],
tagName:'ul'
});


Now if the page is opened, nothing is displayed because the view has not been rendered yet. To display the view, the handlebar template is required.

Now let’s modify the body block of the html page, add the two views you just created to see the effect.

The method to add a handlebar template is <script type="text/x-handlebars">/*View Assistant*/</script>. You can also specify the template name and define it in the data-template-name property. It will be used when we add a list item later.

In the template, you need to add views through the view helper. The syntax is also very simple. Use two curly braces to wrap the view, and use the template keywords to specify the view to be displayed, such as: {{view }}. Other template assistants can be found on the handlebar website: /.

Now add the text box and list view to the page first. The modified body code is as follows:

Copy the codeThe code is as follows:

<body>
<script type="text/x-handlebars">
<span>Please enter to-do items:</span>{{view }}<br/>

{{view }}
</script>
</body>


Now refresh the page and a text box will be displayed with a sentence "Please enter the agency" and a text box. The list will not be displayed because there is no content.

At this time, we can add points to the content, such as content:['a','b','c'], and then refresh the page, and you will find that there are only three small black dots in the list area (if you do not reset the list style). Because you added three items in the content, but the list item has not specified a display template, so the display is empty. In order to let you see the effect, let’s define a display template for the list item. There are two places to be processed here. The first is to add a template with a specified name to the page, and the second is to define the properties of the list item in the list view.

To define a list item, itemViewClass is required, which will pass each content item in and display it with the specified template. First, modify the ListView ListView and add the itemViewClass property to it. This is also a kind of view, so it needs to be used for creation. When creating, specify the template name used to display as itemTemplate. This name will also appear in the handlebar template name of the html. The modified code is as follows:

Copy the codeThe code is as follows:

= ({
content:['a','b','c'],
tagName:'ul',
itemViewClass: ({
templateName:'itemTemplate',
})
});


It's one step away from completing. Now to modify the html, we need to create a new handlebar template in the body, and use the template name given above. The code is as follows:

Copy the codeThe code is as follows:

<script type="text/x-handlebars" data-template-name="itemTemplate">

</script>


Then add a template assistant, and you will use it if you want to pass each content item to the assistant. Add the following code:

Copy the codeThe code is as follows:

<script type="text/x-handlebars" data-template-name="itemTemplate">
{{}}
</script>


After completing it, refresh the page, and now finally display the content in the content, and the template will automatically add the li tag.

Continue to improve our applications. We can't write the content as fixed, so how can users add it? So, now consider saving the item that the user wants to add to an array, and then content to get the content of this array by itself. At the same time, the ember framework supports two-way binding. When the array content is modified, the contents that are bound will also change at the same time, 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 transform the ordinary javascript you passed into into a new ember array object. We named the array used to manage the project todoStore and put it in the controller area of ​​the html page. The code created is as follows:

Copy the codeThe code is as follows:

= ({
content:[]
});


Now you can put the content array in ListView into the todoStore array, and then bind the content in ListView to todoStore. These two objects will be modified as follows:

Copy the codeThe code is as follows:

= ({
contentBinding:'',
tagName:'ul',
itemViewClass: ({
templateName:'itemTemplate'
})
});

/********************
controlle
********************/
= ({
content:['a','b','c']
});


Binding is a suffix, indicating binding, and the attribute value is the bound object, and the content attribute of the object is taken by default. Refresh the page after the modification is completed. If the page you see is the same as before the modification, it means that the modification has been successful. Next, it is time to remove the value in the content, and the data we need will be entered by the user in the text box.

Considering the current interactive process, the user enters content in the text box, press Enter, the program gets the event, calls a method to create a new object, and then gives this new object to todoStore. Due to the binding effect, the list will automatically add one item.

It's time to remodel the text box view below. Do you still remember insertNewline? We can create new projects here. We will use three methods: set() to set the attribute value, get() to get the attribute value, pushObject() to add data, and modify the AddItemView code as follows:

Copy the codeThe code is as follows:

= ({
placeholder: 'Enter to do',
insertNewline:function(){
var item = ('value');
(item);
('value','');
}
});


Now refresh the page, then enter the content, press Enter, the input content will be added to the list, indicating that the modification is successful. If you do not clear the content in the content property of todoStore, there will now be 4 list items.

We are still halfway away from our goal, and we still lack two functions: selecting priority and deleting completed projects.

To add a drop-down list, you can use another convenient view:. We can create one directly in the template, and bind the content of the drop-down list view to another ember object through binding, and then set the default selected priority. The priority also requires binding, so that when selecting on the page, the content in the corresponding ember object will be modified at the same time. First create this ember object, customize the selected property of the object to represent the selected value, and other names are OK. This code will be added to the todoStore object and named as selectController. The code is as follows:

Copy the codeThe code is as follows:

= ({
selected:'low',
content:['high','medium','low']
});


Then add a template assistant and bind the corresponding attribute in the selectController. SelectionBinding is required to bind the selected item, and then give a text prompt, and then add it to the text box template. The modified code is as follows:

Copy the codeThe code is as follows:

<script type="text/x-handlebars">
<span>Please enter to-do items:</span>{{view }}<br/>
<span>Please select priority:</span>{{view contentBinding="" selectionBinding=""}}
{{view }}
</script>


Now, the drop-down list will appear after refreshing the page.

To make the list item also have to take some effort. 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 into todoStore. In addition, the template needs to be modified accordingly, and the creation method of text box view must also be changed. There are a lot of changes this time. In addition, a function of calculating attributes will be used, which will be automatically updated when the dependency attributes change. Name this model TodoModel, put it in the model area, and create the code as follows:

Copy the codeThe code is as follows:

/********************
model
********************/

= ({
status:'',
value:'',
title:function(){
return '['+('status')+']'+('value');
}.property('status','value')
});


status indicates the priority of selection, value indicates the value in the text box, title indicates the content to be displayed on the list item, and these attribute names are customized. The title does not need to be provided because it is set as a computed property, and it depends on the status and value properties, and it is automatically calculated and obtained. The property() method is the method of converting the ember function into a computed property. The following parameters represent the attributes dependent on the title. When the status or value changes, it will be automatically given.

Then modify the insertNewline property of AddItemView, and you need to get two data, one is the content in the text box and the other is the item selected in the drop-down list. I already know how to get the value of the text box, and what about the value of the drop-down list? Don't forget that we have bound the selected item to the selected property in the selectController, just take it from there. The modified AddItemView code is as follows:

Copy the codeThe code is as follows:

= ({
placeholder: 'Enter to do',
elementId:'add',
insertNewline:function(){
var item = ({
status:('selected'),
value:('value')
});
(item);
('value','');
}
});


Now you can instantiate a to-do project through the TodoModel class and add it to the todoStore. Finally, modify the template itemTemplate of the project list to display it. In the template, you need to get the title value of the current project to display it. The code is as follows:

Copy the codeThe code is as follows:

<script type="text/x-handlebars" data-template-name="itemTemplate">
{{}}
</script>


The new to-do items added now show priority.

OK, the last function, delete. In contrast to adding pushObject, removeObject is used. Because it is displayed in each list item, you need to modify the itemViewClass and itemTemplate templates. We add a method in itemViewClass, which is called when the user clicks, and name the method removeItem. The code is as follows:

Copy the codeThe code is as follows:

= ({
contentBinding:'',
tagName:'ul',
itemViewClass: ({
templateName:'itemTemplate',
removeItem:function(){( '' ).removeObject(( 'content' ));}
})
});


Finally, add a link to the itemTemplate template to accept clicks, using the action assistant. The first parameter is the method name. The target attribute is used to specify the object. When clicking, the method under the specified object is called. The modified itemTemplate code is as follows:

Copy the codeThe code is as follows:

<script type="text/x-handlebars" data-template-name="itemTemplate">
{{}} <a href="#" {{action removeItem target="this"}} >X</a>
</script>


Now the newly added projects will have a fork on the right, and the current project will be deleted when clicked.

Finally, some improvements can be made. The delete link is displayed when the mouse moves to the project. To complete this function, you need to modify the itemViewClass and add a logical judgment assistant {{#if}} to the template. You can try it yourself, or you can check out the final complete code.

Copy the 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="/ajax/libs/jquery/1.7.2/"></script>
<script type="text/javascript" src="/downloads/wycats//handlebars-1.."></script>
<script type="text/javascript" src="/downloads/emberjs//ember-1.0.0-pre."></script>
<script>

/********************
application
********************/

= (
{
ready:function(){
('Welcome to do app');
}
}
);

/********************
model
********************/

= ({
status:'',
value:'',
title:function(){
return '['+('status')+']'+('value');
}.property('status','value')
});

/********************
view
********************/
= ({
placeholder: 'Enter to do',
elementId:'add',
insertNewline:function(){
var item = ({
status:('selected'),
value:('value')
});
(item);
('value','');
}
});

= ({
contentBinding:'',
tagName:'ul',
itemViewClass: ({
templateName:'itemTemplate',
removeItem:function(){( '' ).removeObject(( 'content' ));},
mouseEnter:function(){('hover',true);},
mouseLeave:function(){('hover',false);}
})
});



/********************
controlle
********************/
= ({
content:[]
});

= ({
selected:'low',
content:['high','medium','low']
});

</script>
</head>
<body>
<script type="text/x-handlebars">
<span>Please enter to-do items:</span>{{view }}<br/>
<span>Please select priority: </span>{{view contentBinding=""
selectionBinding=""}}
{{view }}
</script>
<script type="text/x-handlebars" data-template-name="itemTemplate">
{{}} {{#if }}<a href="#" {{action removeItem target="this"}} >X</a>{{/if}}
</script>
</body>
</html>