Home > Article > Web Front-end > A closer look at CanJS: Part 2
This is the second in a three-part series that will teach you how to build a contact manager application in JavaScript using CanJS and jQuery. After completing this tutorial, you'll have everything you need to build your own JavaScript applications using CanJS!
In the first part, you created the models, views, and controls needed to display contacts and used fixtures that simulated a REST service.
In this section you will:
You will be adding source files in Part One, so if you haven't done so yet, please catch up first. I'll be here when you're ready.
Routing helps manage browser history and client state in single-page JavaScript applications.
Routing helps manage browser history and client state in single-page JavaScript applications. The hash in the URL contains properties that the application reads and writes. Various parts of the application can listen for these changes and react accordingly, often updating parts of the current page without loading a new page.
can.route
is a special observable that updates and responds to changes in window.location.hash
. Use can.route
to map URLs to properties, resulting in beautiful URLs such as #!filter/all
. If no route is defined, the hash value is simply serialized into a URL-encoded representation, such as #!category=all
.
In this application, routing will be used to filter contacts by category. Add the following code to your contacts.js
file:
can.route( 'filter/:category' ) can.route('', {category: 'all' })
The first line creates a route with a category
attribute that your application will be able to read and write. The second line creates a default route, setting the category
attribute to all
.
A Model.List
is an observable array of model instances. When you define a Model
(such as Contact
), a Model.List
for that type of model is automatically created. We can extend this created Model.List
to add helper functions that operate on a list of model instances.
Contact.List
Two helper functions will be needed to filter the contact list and report how many contacts are in each category. Add this to contacts.js
immediately after the Contact
model:
Contact.List = can.Model.List({ filter: function(category){ this.attr('length'); var contacts = new Contact.List([]); this.each(function(contact, i){ if(category === 'all' || category === contact.attr('category')) { contacts.push(contact) } }) return contacts; }, count: function(category) { return this.filter(category).length; } });
The two auxiliary functions here are:
filter()
Loops through each contact in the list and returns a new Contact.List
of the contacts within the category. this.attr('length')
is included here so EJS will set up the live binding when we use this helper in the view. count()
Use the filter()
helper function to return the number of contacts in a category. Since this.attr('length')
in filter()
, EJS will set the live binding when we use this helper in the view. If you are using helpers in EJS, use
attr()
on a list or instance attribute to set live binding.
Next, you will modify the contactsList.ejs
view to filter contacts based on the category attribute in the hash. In the contactsList.ejs
view, change the parameters passed to the list()
helper to contacts.filter(can.route.attr('category'))
. When finished, your EJS file should look like this:
<ul class="unstyled clearfix"> <% list(contacts.filter(can.route.attr('category')), function(contact){ %> <li class="contact span8" <%= (el)-> el.data('contact', contact) %>> <div class=""> <%== can.view.render('contactView', {contact: contact, categories: categories}) %> </div> </li> <% }) %> </ul>
On the second line, filter()
is called with the current category in can.route
. Since you are using attr()
in both filter()
and can.route
, EJS will set the live binding when either of them changes to re-render your UI.
Now you should be aware of the power of live binding. With a slight adjustment to the view, the app's UI is now fully synchronized not only with the contact list, but also with the category properties defined in the route.
Contacts will be filtered when the category attribute in the hash changes. Now you need a way to list all available categories and change the hash.
First, create a new view to display the list of categories. Save this code as filterView.ejs
in the views
folder:
<ul class="nav nav-list"> <li class="nav-header">Categories</li> <li> <a href="javascript://" data-category="all">All (<%= contacts.count('all') %>)</a> </li> <% $.each(categories, function(i, category){ %> <li> <a href="javascript://" data-category="<%= category.data %>"><%= category.name %> (<%= contacts.count(category.data) %>)</a> </li> <% }) %> </ul>
Let’s look at a few lines of this code and see what they do:
<% $.each(categories, function(i, category){ %>
$.each
Loops through the categories and executes a callback for each category.
<a href="javascript://" data-category="<%= category.data %>"><%= category.name %> (<%= contacts.count(category.data) %>
每个链接都有一个 data-category
属性,该属性将被拉入 jQuery 的数据对象中。稍后,可以使用 <a></a>
标记上的 .data('category')
来访问该值。类别的名称和联系人数量将用作链接测试。实时绑定是根据联系人数量设置的,因为 count()
调用 filter()
其中包含 this.attr('length')
。
can.Control
监听事件
创建实例时,控件会自动绑定看起来像事件处理程序的方法。事件处理程序的第一部分是选择器,第二部分是您要侦听的事件。选择器可以是任何有效的 CSS 选择器,事件可以是任何 DOM 事件或自定义事件。因此,像 'a click'
这样的函数将监听控件元素内任何 <a></a>
标记的点击。
Control 使用事件委托,因此您不必担心在 DOM 更改时重新绑定事件处理程序。
通过将此代码添加到 contacts.js
紧随 Contacts
控件之后来创建管理类别的控件:
Filter = can.Control({ init: function(){ var category = can.route.attr('category') || "all"; this.element.html(can.view('filterView', { contacts: this.options.contacts, categories: this.options.categories })); this.element.find('[data-category="' + category + '"]').parent().addClass('active'); }, '[data-category] click': function(el, ev) { this.element.find('[data-category]').parent().removeClass('active'); el.parent().addClass('active'); can.route.attr('category', el.data('category')); } });
让我们检查一下您刚刚创建的“Filter”控件中的代码:
this.element.html(can.view('filterView', { contacts: this.options.contacts, categories: this.options.categories }));
就像在 Contacts
控件中一样,init()
使用 can.view()
来呈现类别,并使用 html()
将其插入到控件的元素中。
this.element.find('[data-category="' + category + '"]').parent().addClass('active');
查找与当前类别相对应的链接,并将“active”类添加到其父元素。
'[data-category] click': function(el, ev) {
监听与选择器 [data-category]
匹配的任何元素上的 click
事件。
this.element.find('[data-category]').parent().removeClass('active'); el.parent().addClass('active');
从所有链接中删除“活动”类,然后向单击的链接添加“活动”类。
can.route.attr('category', el.data('category'));
使用 jQuery 数据对象中所单击的 <a></a>
的值更新 can.route
中的类别属性。
就像第一部分中的 Contacts
控件一样,您需要创建 Filter
控件的新实例。更新您的文档就绪函数,如下所示:
$(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 }); new Filter('#filter', { contacts: contacts, categories: categories }); }); })
通过此更改,将在 #filter
元素上创建 Filter
控件的实例。它将传递联系人和类别列表。
现在,当您在浏览器中运行应用程序时,您将能够通过单击右侧的类别来过滤联系人:
这就是第二部分的全部内容!以下是我们所取得的成就:
在第三部分中,您将更新现有控件以允许编辑和删除联系人。您还将创建一个新的控件和视图,以便您添加新的联系人。
迫不及待想了解更多信息?该系列的第三部分已发布在这里!
The above is the detailed content of A closer look at CanJS: Part 2. For more information, please follow other related articles on the PHP Chinese website!