Front-end Lightweight MVC Framework Canjs Detailed _ Other

Source: Internet
Author: User
Tags representational state transfer script tag

Select the correct library

It's hard to create a JS app that doesn't have good tools, jquery is just the library that operates the DOM, doesn't provide any foundation for creating apps, which is why we want a special library like 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 for MVC (Model-view-control) patterns, dynamic binding of templates, route support, and memory security. At the same time support JQuery, Zepto, Mootools, YUI, Dojo, there are rich extensions and plug-ins.

In the first part you will learn:
Create control and view view layers (UI templates) to display contacts
Represent data using model layer
Using the fixtures plug-in to simulate Ajax return data
You must be thrilled! Let's start coding code.
Build your folders and HTML.
You first create a folder for your app, and then set up 4 subfolders: CSS, Js,views, and IMG. As follows:
Contacts_manager
Css
Js
Views
Img

Save the following code as index.html:

Copy Code code as follows:

<!doctype html>
<meta charset= "Utf-8" >
<title>canjs Contacts manager</title>
<link rel= "stylesheet" href= "Css/bootstrap.min.css" >
<link rel= "stylesheet" href= "Css/contacts.css" >
<body>
<div class= "Container" >
<div class= "Row" >
<div class= "Span12" >
</div>
</div>
<div class= "Row" >
<div class= "Span3" >
<div class= "OK" >
<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>

At the bottom of the page you load the desired JS (including your APP:contacts.js).
CSS and picture files used in tutorials can be downloaded.

Use the view to create your UI

View is the UI template used to render your app. CANJS support for a variety of template engines, this article with Ejs, CANJS contains and supports dynamic binding.
The EJS template's label is similar to HTML, support contains JS code, three kinds of commonly used tags are as follows:
<% CODE%> Execute JS
<%= CODE%> executes JS and writes non escaped results to the HTML of the current location
The <%== CODE%> executes JS and writes the escaped result to the current location of HTML (for a child template).
The template can be loaded from a file or script tag, and this tutorial is loaded from the EJS file.

Show Contacts

To create a contact, you must first create a Ejs template, save the following code for CONTACTSLIST.EJS into your views folder:

Copy Code code as follows:

<ul class= "Clearfix" >
<% list (contacts, function (contact) {%>
<li class= "Contact Span8" <%= (EL)-> el.data (' contacts ', contact)%>>
<%== can.view.render (' Views/contactview.ejs ', {
Contact:contact, Categories:categories
})%>
</li>
<%})%>
</ul>

Contactlists.ejs will render a contact list, let's analyze This template:

Copy Code code as follows:

<% list (contacts, function (contact) {%>

The callback method in the list () method, if matched with the observer's list, is invoked once the list's data has changed to use dynamic binding.

Copy Code code as follows:

<li class= "Contact Span8" <%= (EL)-> el.data (' contacts ', contact)%>>

The above code generates a <li> with contact data through the element's callback method. After the arrow method executes, the data for the El object is set to the corresponding element.

Copy Code code as follows:

<%== can.view.render (' Views/contactview.ejs ', {
Contact:contact, Categories:categories
})%>

The above code renders the child template Contactview.ejs as a contact person. Can.view.render () returns HTML with templates and data as parameters.

Render a single contact

A child template is a good way to organize your view into manageable chunks. It also makes your templates simple and easy to reuse. This template will be used later in the tutorial to create a contact and save the following code as a Contactview.ejs into the Views folder:

Copy Code code 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 contact's properties are placed in the <input> tag, which allows you to edit the updated user's data.

Activate your view(good literature and art). )

If the EJS process template is useful to attr (), the surrounding code will be managed by the event handler to listen for changes to the corresponding attributes, and the UI associated with the app will be updated when the property changes. This function benefits from the template dynamic binding mechanism, EJS dynamic binding is selective, only the use of attr () will be opened for the corresponding properties.
We use a <input> tag in Contactview.ejs to understand its usage:

Copy Code code as follows:

<input type= "text" name= "name" placeholder= "ADD name"
<%= contact.attr (' name ')? "Value= '" + contact.name + "'": "Class= ' empty '"%>>

The code in the special tag will be turned into an event bound to the Name property of this contact. When the Name property is changed, the event is triggered and the HTML structure is updated.

Use can. Control to handle business logic

Can. Control creates an organized, inherently leak-free, discretionary controller that can be used to create widgets or handle business logic. You can define method binding events in your control by creating a control instance of the required data for a DOM element.
When the element associated with control is removed from the DOM, Contol destroys itself and clears the bound method.
To create a control, give the can by passing in your defined object that contains the function. Control () to implement inheritance. The following events were also passed in.
Each contol instance has several important values and method specifications:
References to This–control instances
this.element– the DOM element you created in the instance
this.options– the parameter objects needed to create the instance
Init () – Called when the instance is created successfully

Manage Contacts

Add the following code fragment to the Contacts.js file to create control for managing contacts:

Copy Code code as follows:

Contacts = can. Control ({
Init:function () {
This.element.html (Can.view (' Views/contactslist.ejs '), {
Contacts:this.options.contacts,
Categories:this.options.categories
}));
}
})

When an instance of Contacts is created, init () does two things:
Use Can.view () to render the contact. Can.view () receives two parameters: a file or stript tag containing templates and data; a documentfragment (a lightweight container for managing DOM elements) is returned.
Use jquery.html () to insert the documentfragment of Can.view () into the control's element

Use model to represent data

Model is the abstraction layer of app data. This app uses two model: a corresponding contact person, a corresponding category. Add the following code to the Contacts.js:

Copy Code code 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 5 methods that may define CRUD data, respectively, FindAll, FindOne, create, update, and destroy. You can rewrite these methods, but the best way to do this is to use the REST service (representational state Transfer Express). As the code above, you are relieved to ignore the static methods that are not used in the app.

The key point here is that the model example is actually derived from the Canjs ' observables '. Can. Observe provides the object's observer pattern can. Observe.list provides an array of observation patterns. This means that you can use attr () to get and set data, while listening for data changes.
The FindAll () method returns a Model.list, which is the can when the element is added or removed. The event triggered by the observe.list.

Using fixture to imitate rest

Fixture intercepts an AJAX request and simulates the response through a file or method. This is useful for testing, or when the backend is not ready. Fixture is what app's model emulates rest needs.
First, you need to prepare some data to fixture, add the following code to:

Copy Code code as follows:

var CONTACTS = [
{
Id:1,
Name: ' William ',
Address: ' 1 canjs Way ',
Email: ' William@husker.com ',
Phone: ' 0123456789 ',
Category: ' Co-workers '
},
{
Id:2,
Name: ' Laura ',
Address: ' 1 canjs Way ',
Email: ' Laura@starbuck.com ',
Phone: ' 0123456789 ',
Category: ' Friends '
},
{
Id:3,
Name: ' Lee ',
Address: ' 1 canjs Way ',
Email: ' Lee@apollo.com ',
Phone: ' 0123456789 ',
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 the data, you want to connect it to fixture to simulate rest. Can.fixture () receives two parameters. We want to intercept the URL and we answer the file and method. Usually the URLs you want to intercept are dynamic and follow a pattern. You need to add the wildcard characters enclosed in the URL.

Add the following code to Contacts.js:

Copy Code code 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 4 fixture simulate contact model's get, POST, put and DELETE responses, and 5th simulate Category model's get response.

Start app

Your app has a model for managing data, rendering contact View, and organizing all this control. All we have to do now is start the app. Now and need to kickstart the application!
Add the following code to the Contacts.js:

Copy Code code 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 take a look at this piece of code:

Copy Code code as follows:

$ (document). Ready (function () {

Use the Jquery.ready method to listen for Dom ready.

Copy Code code as follows:

$.when (Category.findall (), Contact.findall ()). Then (
function (Categoryresponse, contactresponse) {

Call the two model FindAll () method to get the type of all contacts, because FindAll () has a delay, $.when () ensures that two requests are completed at the same time before the callback method is executed.

Copy Code code as follows:

var categories = Categoryresponse[0],
contacts = Contactresponse[0];

Gets the dataset for the model instance from two FindAll () methods. is the first element of the array returned by the answer.

Copy Code code as follows:

New Contacts (' #contacts ', {
Contacts:contacts,
Categories:categories
});

Create control of the contact for the #contacts element. Contact and type data sets are passed in control.
Use your browser to open your app, and you'll see a list of contacts like the following:

Summarize

This is the first of a series of tutorials that you have learned about the core of Canjs:
Models the abstraction layer of your app data
Views convert data to HTML template
Controls Organization Associates Everything

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.