Detailed description of the front-end lightweight MVC Framework CanJS and mvccanjs
Select the correct database
It is very difficult to create a js app without a good tool. jQuery only operates the DOM library and does not provide any basis for creating the APP. That is why we need a dedicated library similar to CanJS.
CanJS is a lightweight MVC library that provides the tools you need to create a js app.
CanJS is a lightweight MVC library that provides the tools you need to create a js app. It provides a basic framework with the Model-View-Control mode, dynamic template binding, support for route, and memory security. It also supports jQuery, Zepto, Mootools, YUI, and Dojo, and has a wide range of extensions and plug-ins.
In the first part, you will learn:
Create Control layer and View layer (UI template) to display contacts
Use the Model layer to represent data
Use the fixtures plug-in to simulate ajax return data
You must be excited! Let's start code.
Create your folder and HTML
Create a folder for your APP, and create four sub-folders under the Directory: css, js, views, and img. As follows:
Contacts_manager
Css
Js
Views
Img
Save the following code as index.html:
Copy codeThe Code is as follows:
<! Doctype html>
<Html lang = "en">
<Head>
<Meta charset = "UTF-8">
<Title> CanJS Contacts Manager </title>
<Link rel = "stylesheet" href = "css/bootstrap.min.css">
<Link rel = "stylesheet" href = "css/contacts.css">
</Head>
<Body>
<Div class = "container">
<Div class = "row">
<Div class = "span12">
<H1> Contacts Manager </Div>
</Div>
<Div class = "row">
<Div class = "span3">
<Div class = "well">
<Nav id = "filter"> </nav>
</Div>
</Div>
<Div class = "span9">
<Div id = "create"> </div>
<Div id = "contacts"> </div>
</Div>
</Div>
</Div>
<Script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"> </script>
<Script src = "js/can. jquery. min. js"> </script>
<Script src = "js/can. fixture. js"> </script>
<Script src = "js/contacts. js"> </script>
</Body>
</Html>
Load the required JS (including your APP: contacts. js) at the bottom of the page ).
CSS and image files used in this tutorial can be downloaded.
Use View to build your UI
View is the UI template used to render your APP. CanJS supports multiple template engines. This document uses EJS. CanJS includes and supports dynamic binding.
The tags of the ejs template are similar to those of the HTML template and support JavaScript code. The three common tags are as follows:
<% CODE %> execute JS
<% = CODE %> execute JS and write non-escape results to the HTML at the current location
<% = CODE %> execute JS and write the escape result to the HTML at the current position (for subtemplate ).
The template can be loaded from the file or script tag. This tutorial loads the template from the EJS file.
Show contacts
To create a contact, you must first create an EJS template and save the following code as contactsList. ejs to your views Folder:
Copy codeThe Code is as follows:
<Ul class = "clearfix">
<% List (contacts, function (contact) {%>
<Li class = "contact span8" <% = (el)-> el. data ('Contact ', contact) %>
<% = Can. view. render ('Views/contactView. ejs ',{
Contact: contact, categories: categories
}) %>
</Li>
<%}) %>
</Ul>
ContactLists. ejs renders a contact list. Let's analyze this template:
Copy codeThe Code is as follows:
<% List (contacts, function (contact) {%>
If the callback method in the list () method is used together with the list Method configured with the observer, the dynamic binding is used for repeated calls once the list data changes.
Copy codeThe Code is as follows:
<Li class = "contact span8" <% = (el)-> el. data ('Contact ', contact) %>
The above code generates a contact data <li> using the element callback method. After the method behind the arrow is executed, set the data of the el object to the corresponding element.
Copy codeThe Code is as follows:
<% = Can. view. render ('Views/contactView. ejs ',{
Contact: contact, categories: categories
}) %>
The code above renders the subtemplate contactView. ejs into a contact. Can. view. render () returns HTML with template and data as parameters.
Render a single contact
A sub-template is a good way to organize a view into manageable blocks. It also makes your template simple and easy to reuse. This template will be used later in the tutorial to create contacts and save the following code as contactView. ejs to the views Folder:
Copy codeThe Code is as follows:
<A href = "javascript: //" class = "remove"> <I class = "icon-remove"> </I> </a>
<Form>
<Div class = "row">
<Div class = "span2">
</Div>
<Div class = "span3">
<Input type = "text" name = "name" placeholder = "Add Name"
<% = Contact. attr ('name ')? "Value = '" + contact. name + "'": "class = 'empty'" %>
<Select name = "category">
<% $. Each (categories, function (I, category) {%>
<Option value = "<% = category. data %>" <% = contact. category === category. data? "Selected": "" %>
<% = Category. name %>
</Option>
<%}) %>
</Select>
</Div>
<Div class = "span3">
<Label> Address </label>
<Input type = "text" name = "address"
<% = Contact. attr ('address ')? "Value = '" + contact. address + "'": "class = 'empty'" %>
<Label> Phone </label>
<Input type = "text" name = "phone"
<% = Contact. attr ('phone ')? "Value = '" + contact. phone + "'": "class = 'empty'" %>
<Label> Email </label>
<Input type = "text" name = "email"
<% = Contact. attr ('email ')? "Value = '" + contact. email + "'": "class = 'empty'" %>
</Div>
</Div>
</Form>
The attributes of the contact are all placed in the <input> tag, which allows you to edit and update user information.
Activate your View(Good literature and art ..)
If attr () is used in the processing template process of EJS, the code around it will be managed by the event processor, and the corresponding attribute changes will be monitored. When the attribute changes, the associated UI in the APP will be updated. This function is applicable to the template dynamic binding mechanism. The dynamic binding of EJS is optional. It is enabled only when attr () is used.
We use the <input> label in contactView. ejs to understand its usage:
Copy codeThe Code is as follows:
<Input type = "text" name = "name" placeholder = "Add Name"
<% = Contact. attr ('name ')? "Value = '" + contact. name + "'": "class = 'empty'" %>
The code in the special mark is converted into an event bound to the name attribute of this contact. When the name attribute changes, the event is triggered and the HTML structure is updated.
Use can. Control to process business logic
Can. Control creates an organizational structure with no internal leakage and full Control. It can be used to create widgets or process business logic. You can create a Control instance for a DOM element through the required data. You can define the method binding event in your Control.
When the elements associated with the Control are deleted from the DOM, Contol will destroy itself and clear the bound method.
To create a Control, pass in the defined object containing the function to can. Control () to implement inheritance. Next, the event is also transmitted.
Each Contol instance has several important values and method specifications:
Reference of this-Control instance
This. element-the DOM element you created in the instance
This. options-parameter object required for instance Creation
Init ()-called when the instance is successfully created
Manage contacts
Add the following code snippet to the contacts. js file to create a Control for managing contacts:
Copy codeThe Code is as follows:
Contacts = can. Control ({
Init: function (){
This.element.html (can. view ('Views/contactsList. ejs ',{
Contacts: this. options. contacts,
Categories: this. options. categories
}));
}
})
When a Contacts instance is created, init () does two things:
Use can. view () to render contacts. Can. view () receives two parameters: files with templates and data, or strsight labels. A documentFragment (a lightweight container that manages DOM elements) is returned ).
Use jquery.html () to insert the documentFragment of can. view () into the Control element.
Use Model to present data
Model is the abstraction layer of APP data. This APP uses two models: one corresponding contact and one corresponding category. Add the following code to contacts. js:
Copy codeThe Code is as follows:
Contact = can. Model ({
FindAll: 'Get/contacts ',
Create: "POST/contacts ",
Update: "PUT/contacts/{id }",
Destroy: "DELETE/contacts/{id }"
},{});
Category = can. Model ({
FindAll: 'Get/categories'
},{});
A model has five methods that may be defined as CRUD data: findAll, findOne, create, update, and destroy. You can override these methods, but the best way is to use the REST Service (Representational State Transfer declarative State Transfer ). Just like the above code, you can safely ignore the static methods that are not used in the APP.
It is important to note that the model instance actually comes from the 'observables 'of CanJS '. Can. Observe provides the object's observer mode. can. Observe. List provides the array's observation mode. This means that you can get and set data through attr () and listen for data changes at the same time.
The findAll () method returns a Model. list, which is the event triggered by can. Observe. List when an element is added or removed.
Use Fixture to simulate Rest
Fixture intercepts AJAX requests and simulates responses through files or methods. This is useful for testing, or when the backend is not ready. Fixture is required to simulate the REST of the APP model.
First, you need to prepare some data for fixture and add the following code:
Copy codeThe Code is as follows:
Var CONTACTS = [
{
Id: 1,
Name: 'william ',
Address: '1 CanJS way ',
Email: 'William @ husker.com ',
Phone: '000000 ',
Category: 'co-workers'
},
{
Id: 2,
Name: 'Laura ',
Address: '1 CanJS way ',
Email: 'ura @ starbuck.com ',
Phone: '000000 ',
Category: 'friends'
},
{
Id: 3,
Name: 'lil ',
Address: '1 CanJS way ',
Email: 'Lee @ apollo.com ',
Phone: '000000 ',
Category: 'Family'
}
];
Var CATEGORIES = [
{
Id: 1,
Name: 'Family ',
Data: 'Family'
},
{
Id: 2,
Name: 'friends ',
Data: 'friends'
},
{
Id: 3,
Name: 'co-workers ',
Data: 'co-workers'
}
];
With data, connect it to fixture to simulate REST. Can. fixture () receives two parameters. The URL we want to intercept and the file and method used for our response. The URLs you want to intercept are dynamic and follow the same pattern. Add the wildcard characters included in {} to the URL.
Add the following code to contacts. js:
Copy codeThe Code is as follows:
Can. fixture ('get/contacts', function (){
Return [CONTACTS];
});
Var id = 4;
Can. fixture ("POST/contacts", function (){
Return {id: (id ++ )}
});
Can. fixture ("PUT/contacts/{id}", function (){
Return {};
});
Can. fixture ("DELETE/contacts/{id}", function (){
Return {};
});
Can. fixture ('get/categories ', function (){
Return [CATEGORIES];
});
The first four fixture simulate the GET, POST, PUT, and DELETE responses of the Contact model, and 5th simulate the GET responses of the Category model.
Start APP
Your APP has a Model for data management, rendering the View of contacts, and controlling all these items. Now you have to start the APP. Now you need to kickstart the application!
Add the following code to contacts. js:
Copy codeThe Code is as follows:
$ (Document). ready (function (){
$. When (Category. findAll (), Contact. findAll (). then (
Function (categoryResponse, contactResponse ){
Var categories = categoryResponse [0],
Contacts = contactResponse [0];
New Contacts ('# contacts ',{
Contacts: contacts,
Categories: categories
});
});
});
Let's analyze this Code:
Copy codeThe Code is as follows:
$ (Document). ready (function (){
Use the jQuery. ready method to listen to the DOM ready.
Copy codeThe Code is as follows:
$. When (Category. findAll (), Contact. findAll (). then (
Function (categoryResponse, contactResponse ){
Call the findAll () method of two models to obtain the type of all contacts. Because the findAll () has a delay, $. when () ensures that the callback method is executed only after both requests are completed.
Copy codeThe Code is as follows:
Var categories = categoryResponse [0],
Contacts = contactResponse [0];
Obtain the dataset of the corresponding Model instance from the two findAll () methods. Is the first element of the returned array.
Copy codeThe Code is as follows:
New Contacts ('# contacts ',{
Contacts: contacts,
Categories: categories
});
Create a Contact Control for the # contacts element. Send the contact and type dataset to Control.
Open your APP in a browser and you will see the following contact list:
Summary
This is the first article in the tutorial series. You have learned about the core of CanJS:
Models the abstraction layer of your APP data
Views converts data into HTML templates
Controls
Is there a front-end (js) MVC framework without the "front-end template" technology?
Of course, it's convenient to use templates.
Do you want to write innerHTML one by one?
Advantages and disadvantages of asp net mvc Framework
Advantages of MVC:
1. It is easy to maintain during large-scale development and has good scalability.
2. You can have full control permissions on HTML, which is friendly to the front-end.
3. Ability to perform unit tests to ensure the implementation of functions.
Disadvantages:
1. There are not so many ready-to-use controls, and the development efficiency is relatively low (especially for cainiao)
2. It is difficult to process large data because there is no ready-made girdview control. Although the html structure generated by this control is extremely complex, it is very good for processing large amounts of complicated data. However, there are very few such massive and complex data on websites. Many cainiao use this cannon to attack mosquitoes, which is a waste and inefficient task. This control should not be recommended for website development.
The new cainiao and webform are good when rapid development is required.
Scalability is required. MVC is recommended for high control. However, the threshold for using this framework is relatively high. If you only understand the webform development form of asp.net, because webform has already done too many things for you, in other words, you do not know what real web development is like. On the contrary, asp users are more familiar with php.
MVC and webform have their own purposes.
However, you should not use the asp.net mvc framework:
You are not very familiar with Polymorphism
You don't like building applications on this framework
You rely on many third-party UI controls
You do not like to use open-source programs