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:
- Create controls and views to display categories.
- Use controls to listen to events.
- Use routing to filter contacts.
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.
Set routing
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
.
Use model instance list
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 newContact.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 thefilter()
helper function to return the number of contacts in a category. Sincethis.attr('length')
infilter()
, 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.
Filter Contacts
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.
Display categories
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
控件的实例。它将传递联系人和类别列表。
现在,当您在浏览器中运行应用程序时,您将能够通过单击右侧的类别来过滤联系人:
总结
这就是第二部分的全部内容!以下是我们所取得的成就:
- 创建了一个用于侦听事件并管理类别的控件
- 设置路由以按类别过滤联系人
- 调整了您的视图,以便实时绑定使您的整个 UI 与数据层保持同步
在第三部分中,您将更新现有控件以允许编辑和删除联系人。您还将创建一个新的控件和视图,以便您添加新的联系人。
迫不及待想了解更多信息?该系列的第三部分已发布在这里!
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!

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft