没有合适的资源?快使用搜索试试~ 我知道了~
首页Backbone.js应用开发指南:从入门到实践
Backbone.js应用开发指南:从入门到实践
需积分: 16 0 下载量 86 浏览量
更新于2024-07-24
收藏 2.47MB PDF 举报
"《Developing Backbone.js Applications》是一本由Addy Osmani编著的专业书籍,专注于介绍Backbone.js框架的开发实践与理论。Backbone.js是JavaScript MVC(模型-视图-控制器)架构的轻量级实现,它在前端开发中被广泛应用,尤其适合构建单页应用(SPA,Single Page Application)。
在本书中,作者首先回顾了MVC(Model-View-Controller)设计模式的基本概念,如Smalltalk-80 MVC的起源,以及现代软件开发中所熟知的MVC架构。MVC的核心在于将数据处理、显示逻辑和用户交互分离,提高了代码的可维护性和复用性。
章节2详细讨论了Backbone.js如何实现在MVC的基础上进行扩展。模型(Models)代表数据存储和操作,视图(Views)负责界面渲染,而控制器(Controllers)则协调这两者间的交互。书中还比较了Spine.js和Backbone.js在控制器设计上的不同,以帮助读者理解框架之间的差异。
书中的“Delving deeper”部分深入探讨了MVC模式在实际项目中的应用价值,以及MVP(Model-View-Presenter)模式的兴起,两者之间的选择取决于项目的具体需求。此外,作者提供了快速概览(Fast facts)来帮助读者迅速掌握Backbone.js的核心特性。
在“Backbone.js”这一章,作者解释了为什么要选择Backbone.js作为开发工具,包括其简洁的设计、对其他库(如Underscore.js)的依赖以及如何创建和管理模型、视图和集合(Collections)。同时,书里也介绍了路由器(Routers)的作用,如Backbone.history在应用程序路由中的关键作用。
为了简化开发过程,作者还提及了自动化Backbone.js项目结构生成的工具,这有助于开发者快速搭建基础框架。
《Developing Backbone.js Applications》是一本实用的指南,适合希望学习和使用Backbone.js进行Web应用开发的开发者,无论你是对MVC设计模式有深入理解,还是初次接触这个框架,都能从中获益匪浅。通过阅读这本书,读者可以掌握Backbone.js的精髓,并将其应用于实际项目中,提升应用的结构化和性能。"
In the context of JavaScript frameworks that support MVC/MV*, it is worth looking
more closely at JavaScript templating and its relationship to Views.
It has long been considered bad practice (and computationally expensive) to manually
create large blocks of HTML markup in-memory through string concatenation. De-
velopers using this technique often find themselves iterating through their data, wrap-
ping it in nested divs and using outdated techniques such as document.write to inject
the “template” into the DOM. This approach often means keeping scripted markup
inline with standard markup, which can quickly become difficult to read and maintain,
especially when building large applications.
JavaScript templating libraries (such as Handlebars.js or Mustache) are often used to
define templates for views as HTML markup containing template variables. These
template blocks can be either stored externally or within script tags with a custom type
(e.g “text/template”). Variables are delimited using a variable syntax (e.g {{name}}).
Javascript template libraries typically accept data in JSON, and the grunt work of pop-
ulating templates with data is taken care of by the framework itself. This has a several
benefits, particularly when opting to store templates externally as this can let applica-
tions load templates dynamically on an as-needed basis.
Let’s compare two examples of HTML templates. One is implemented using the pop-
ular Handlebars.js library, and the other uses Underscore’s “microtemplates”.
Handlebars.js:
<li class="photo">
<h2>{{caption}}</h2>
<img class="source" src="{{src}}"/>
<div class="meta-data">
{{metadata}}
</div>
</li>
Underscore.js Microtemplates:
<li class="photo">
<h2><%= caption %></h2>
<img class="source" src="<%= src %>"/>
<div class="meta-data">
<%= metadata %>
</div>
</li>
You may also use double curly brackets (i.e {{}}) (or any other tag you feel comfortable
with) in Microtemplates. In the case of curly brackets, this can be done by setting the
Underscore templateSettings attribute as follows:
_.templateSettings = { interpolate : /\{\{(.+?)\}\}/g };
A note on navigation and state
It is also worth noting that in classical web development, navigating between inde-
pendent views required the use of a page refresh. In single-page JavaScript applications,
MVC As We Know It | 7
however, once data is fetched from a server via Ajax, it can be dynamically rendered in
a new view within the same page. Since this doesn’t automatically update the URL, the
role of navigation thus falls to a “router”, which assists in managing application state
(e.g allowing users to bookmark a particular view they have navigated to). As routers
are however neither a part of MVC nor present in every MVC-like framework, I will
not be going into them in greater detail in this section.
Controllers
Controllers are an intermediary between models and views which are classically re-
sponsible for two tasks: they both update the view when the model changes and update
the model when the user manipulates the view.
In our photo gallery application, a controller would be responsible for handling changes
the user made to the edit view for a particular photo, updating a specific photo model
when a user has finished editing.
It’s with controllers that most JavaScript MVC frameworks depart from this interpre-
tation of the MVC pattern. The reasons for this vary, but in my opinion, Javascript
framework authors likely initially looked at server-side interpretations of MVC (such
as Ruby on Rails), realized that that approach didn’t translate 1:1 on the client-side,
and so re-interpreted the C in MVC to solve their state management problem. This was
a clever approach, but it can make it hard for developers coming to MVC for the first
time to understand both the classical MVC pattern and the “proper” role of controllers
in other non-Javascript frameworks.
So does Backbone.js have Controllers? Not really. Backbone’s Views typically contain
“controller” logic, and Routers (discussed below) are used to help manage application
state, but neither are true Controllers according to classical MVC.
In this respect, contrary to what might be mentioned in the official documentation or
in blog posts, Backbone is neither a truly MVC/MVP nor MVVM framework. It’s in
fact better to see it a member of the MV* family which approaches architecture in its
own way. There is of course nothing wrong with this, but it is important to distinguish
between classical MVC and MV* should you be relying on discussions of MVC to help
with your Backbone projects.
Controllers in Spine.js vs Backbone.js
Spine.js
We now know that controllers are traditionally responsible for updating the view when
the model changes (and similarly the model when the user updates the view). Since
Backbone doesn’t have its own explicit controllers, it’s useful to review the controller
from another MVC framework to appreciate the difference in implementations. Let’s
take a look at Spine.js:
8 | Chapter 1: Introduction
In this example, we’re going to have a controller called PhotosController which will be
in charge of individual photos in the application. It will ensure that when the view
updates (e.g a user edited the photo meta-data) the corresponding model does too.
(Note: We won’t be delving heavily into Spine.js beyond this example, but it’s worth
looking at it to learn more about Javascript frameworks in general.)
// Controllers in Spine are created by inheriting from Spine.Controller
var PhotosController = Spine.Controller.sub({
init: function(){
this.item.bind("update", this.proxy(this.render));
this.item.bind("destroy", this.proxy(this.remove));
},
render: function(){
// Handle templating
this.replace($("#photoTemplate").tmpl(this.item));
return this;
},
remove: function(){
this.$el.remove();
this.release();
}
});
In Spine, controllers are considered the glue for an application, adding and responding
to DOM events, rendering templates and ensuring that views and models are kept in
sync (which makes sense in the context of what we know to be a controller).
What we’re doing in the above example is setting up listeners in the update and
destroy events using render() and remove(). When a photo entry gets updated, we re-
render the view to reflect the changes to the meta-data. Similarly, if the photo gets
deleted from the gallery, we remove it from the view. In case you were wondering about
the tmpl() function in the code snippet: in the render() function, we’re using this to
render a JavaScript template called #photoTemplate which simply returns a HTML
string used to replace the controller’s current element.
What this provides us with is a very lightweight, simple way to manage changes between
the model and the view.
Backbone.js
Later on in this section we’re going to revisit the differences between Backbone and
traditional MVC, but for now let’s focus on controllers.
In Backbone, controller logic is shared between Backbone.View and Backbone.Router.
Earlier releases of Backbone contained something called Backbone.Controller, but it
was renamed to Router to clarify its role.
A Router’s main purpose is to translate URL requests into application states. When a
user browses to the URL www.example.com/photos/42, a Router could be used to
MVC As We Know It | 9
Downloa d f r o m W o w ! e B o o k < w w w.woweb o o k . c o m >
show the photo with that ID, and to define what application behavior should be run
in response to that request. Routers can contain traditional controller responsibilities,
such as binding the events between models and views, or rendering parts of the page.
However, Backbone contributor Tim Branyen has pointed out that it’s possible to get
away without needing Backbone.Router at all for this, so a way to think about it using
the Router paradigm is probably:
var PhotoRouter = Backbone.Router.extend({
routes: { "photos/:id": "route" },
route: function(id) {
var item = photoCollection.get(id);
var view = new PhotoView({ model: item });
something.html( view.render().el );
}
}):
What does MVC give us?
To summarize, the separation of concerns in MVC facilitates modularization of an
application’s functionality and enables:
• Easier overall maintenance. When updates need to be made to the application it
is clear whether the changes are data-centric, meaning changes to models and pos-
sibly controllers, or merely visual, meaning changes to views.
• Decoupling models and views means that it’s straight-forward to write unit tests
for business logic
• Duplication of low-level model and controller code is eliminated across the appli-
cation
• Depending on the size of the application and separation of roles, this modularity
allows developers responsible for core logic and developers working on the user-
interfaces to work simultaneously
Delving deeper
Right now, you likely have a basic understanding of what the MVC pattern provides,
but for the curious, we’ll explore it a little further.
The GoF (Gang of Four) do not refer to MVC as a design pattern, but rather consider
it a “set of classes to build a user interface”. In their view, it’s actually a variation of
three other classical design patterns: the Observer (Pub/Sub), Strategy and Composite
patterns. Depending on how MVC has been implemented in a framework, it may also
use the Factory and Decorator patterns. I’ve covered some of these patterns in my other
free book, JavaScript Design Patterns For Beginners if you would like to read into them
further.
10 | Chapter 1: Introduction
As we’ve discussed, models represent application data, while views handle what the
user is presented on screen. As such, MVC relies on Pub/Sub for some of its core com-
munication (something that surprisingly isn’t covered in many articles about the MVC
pattern). When a model is changed it “publishes” to the rest of the application that it
has been updated. The “subscriber”–generally a Controller–then updates the view ac-
cordingly. The observer-viewer nature of this relationship is what facilitates multiple
views being attached to the same model.
For developers interested in knowing more about the decoupled nature of MVC (once
again, depending on the implementation), one of the goals of the pattern is to help
define one-to-many relationships between a topic and its observers. When a topic
changes, its observers are updated. Views and controllers have a slightly different re-
lationship. Controllers facilitate views to respond to different user input and are an
example of the Strategy pattern.
Summary
Having reviewed the classical MVC pattern, your should now understand how it allows
developers to cleanly separate concerns in an application. You should also now appre-
ciate how JavaScript MVC frameworks may differ in their interpretation of MVC, and
how they share some of the fundamental concepts of the original pattern.
When reviewing a new JavaScript MVC/MV* framework, remember - it can be useful
to step back and consider how it’s opted to approach Models, Views, Controllers or
other alternatives, as this can better help you grok how the framework expects to be
used.
MVP
Model-view-presenter (MVP) is a derivative of the MVC design pattern which focuses
on improving presentation logic. It originated at a company named Taligent in the early
1990s while they were working on a model for a C++ CommonPoint environment.
Whilst both MVC and MVP target the separation of concerns across multiple compo-
nents, there are some fundamental differences between them.
For the purposes of this summary we will focus on the version of MVP most suitable
for web-based architectures.
Models, Views & Presenters
The P in MVP stands for presenter. It’s a component which contains the user-interface
business logic for the view. Unlike MVC, invocations from the view are delegated to
the presenter, which are decoupled from the view and instead talk to it through an
interface. This allows for all kinds of useful things such as being able to mock views in
unit tests.
MVP | 11
剩余154页未读,继续阅读
非著名coder
- 粉丝: 5
- 资源: 30
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- 平尾装配工作平台运输支撑系统设计与应用
- MAX-MIN Ant System:用MATLAB解决旅行商问题
- Flutter状态管理新秀:sealed_flutter_bloc包整合seal_unions
- Pong²开源游戏:双人对战图形化的经典竞技体验
- jQuery spriteAnimator插件:创建精灵动画的利器
- 广播媒体对象传输方法与设备的技术分析
- MATLAB HDF5数据提取工具:深层结构化数据处理
- 适用于arm64的Valgrind交叉编译包发布
- 基于canvas和Java后端的小程序“飞翔的小鸟”完整示例
- 全面升级STM32F7 Discovery LCD BSP驱动程序
- React Router v4 入门教程与示例代码解析
- 下载OpenCV各版本安装包,全面覆盖2.4至4.5
- 手写笔画分割技术的新突破:智能分割方法与装置
- 基于Koplowitz & Bruckstein算法的MATLAB周长估计方法
- Modbus4j-3.0.3版本免费下载指南
- PoqetPresenter:Sharp Zaurus上的开源OpenOffice演示查看器
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功