SlideShare una empresa de Scribd logo
1 de 47
Descargar para leer sin conexión
前端MVC 
之Backbone 
miyukizhang
提纲 
• Why 
• What 
• 案例 
• Questions
提纲 
• Why 
• What 
• 案例 
• Questions
Why 
• JS开发现状: 
1. 数据和视图耦合过紧 
var list = “”; 
$.each (data, function(index. value){ 
list += “<li id=‘item-­‐‑” + value.Id + “’>” + value.Name + “</li>”; 
}); 
$(“ul”).append(list);
Why 
2. 回调过多 
$.getJSON(“/Items”, function(data){ 
var list = “”; 
$.each(data, function(index, value){ 
list += “<li id=‘item-­‐‑” + value.Id + “’>” + value.Name + “</li>”; 
}); 
$(“ul”).append(list); 
$(“li”).click(function(){ 
var $this = $(this); 
var id = $this.aUr(“id”).replace(“items-­‐‑”, “”); 
$.post(“/Items”, {id: id}, function(){ 
$this.fadeOut(function(){ 
$this.remove(); 
}); 
}); 
}); 
});
Why 
• 遇到的问题: 
o 程序结构不清晰,不利于理解 
o 大量的字符串拼接 
o 大量的回调函数 
o 难以维护
Why 
• 现代Web App的特点: 
o 页面不整体刷新 
o 与服务器的交互均由Ajax完成 
o 服务器只负责提供数据接口 
o 逻辑、展现、行为都交给JavaScript处理 
o 速度更快、体验更好
Why 
• 遇到的问题: 
o JS开发量大、逻辑复杂 
o 如果整个App只有一个URL,不便于收藏和传播 
o 无浏览器历史记录,浏览器前进后退按钮失效 
o 对搜索引擎不友好
Why 
• So,我们需要一个解决方案: 
o 使程序结构清晰、便于理解 
o 将数据与UI解耦 
o 不存在回调函数 
o 减少重复劳动 
o 易于维护和扩展
Why 
• So,我们需要一个解决方案(更实际地): 
o 基于数据层的RESTful Web服务 
o 事件(数据与UI解耦) 
o 一个牢固的路由系统 
o 一个模板引擎 
o 一个可以解决上面所有需求轻量JavaScript框架
Why 
今天的话题:
提纲 
• Why 
• What 
• 案例 
• Questions
What 
Backbone.js gives structure to web 
applications by providing models with key-value 
binding and custom 
events, collections with a rich API of 
enumerable functions, views with declarative 
event handling, and connects it all to your 
existing API over a RESTful JSON interface.
What 
Backbone.js gives structure to web 
applications by providing models with key-value 
binding and custom 
events, collections with a rich API of 
enumerable functions, views with declarative 
event handling, and connects it all to your 
existing API over a RESTful JSON interface.
What 
Backbone.js gives structure to web 
applications by providing models with key-value 
binding and custom 
events, collections with a rich API of 
enumerable functions, views with declarative 
event handling, and connects it all to your 
existing API over a RESTful JSON interface.
What 
Backbone.js gives structure to web 
applications by providing models with key-value 
binding and custom 
events, collections with a rich API of 
enumerable functions, views with declarative 
event handling, and connects it all to your 
existing API over a RESTful JSON interface.
What 
Backbone.js gives structure to web 
applications by providing models with key-value 
binding and custom 
events, collections with a rich API of 
enumerable functions, views with declarative 
event handling, and connects it all to your 
existing API over a RESTful JSON interface.
What 
• 依赖: 
o Underscore.js 
o jQuery 或者 Zepto 
o Json2.js
What 
MVC
What 
MVC 
Model / Collection 数据(模型)
What 
MVC 
Model / Collection 数据(模型) 
Template 展现层(视图)
What 
MVC 
Model / Collection 数据(模型) 
Template 展现层(视图) 
View 控制器
What 
MVC 
Model / Collection 数据(模型) 
Template 展现层(视图) 
View 控制器 
Router ???
What 
MVC 
Model / Collection 数据(模型) 
Template 展现层(视图) 
View 控制器 
Router ??? 
Controller
What 
• 模型(Model) 
o 用来存放应用的所有数据对象 
o 能够被创建、验证和销毁等 
o 属性的改变会触发“change”事件
What 
模型 
• Fetch HTTP GET /url 
• Save(new) HTTP POST /url 
• Save HTTP PUT /url/id 
• Destroy HTTP DELETE /url/id
What 
var Comment = Backbone.Model.extend(); 
var comment = new Comment({ 
id: 6378, 
text: “高富帅的设计”, 
created_at: “3小时前”, 
user: { 
id: ”sasaliu”, 
user_name_zh: “刘沙” 
} 
});
• extend 
• constructor/initialize 
• get 
• set 
• escape 
• has 
• unset 
• clear 
• id 
• cid 
• attributes 
• defaults 
• toJSON 
comment.get(‘text’ 
); //高富帅的设计 
comment.set( 
{‘text’:”<script>console.log(‘xss’)</script>”}, 
{silent: true} 
); 
comment.escape(‘text’);// 
&lt;script&gt;console.log(&#x27xss&#x27)&lt;&#x2F; 
script&gt; 
comment.has(‘city’ 
);//false 
comment.unset(‘text’); 
//触发’change’事件 
var Comment = new Backbone.Model.extend({ 
//hash or function() 
defaults: { 
‘root’: ‘tea.cdc.com’ 
}, 
initialize: function(){…} 
}); 
var comment = new Comment(); 
comment.get(‘root’); 
//’tea.cdc.com’
• fetch 
• save 
• desrtoy 
• validate 
• url 
• urlRoot 
• parse 
• clone 
• isNew 
• change 
• hasChanged 
• changedAttributes 
• previous 
• previousAttributes 
var Comment = new Backbone.Model.extend({ 
urlRoot: ‘/comments’, 
initialize: function(aUrs){ … } 
}); 
var comment = new Comment({id: 123456}); 
comment.url(); 
// ‘/comments/123456’ 
comment.fetch(); 
var Comment = new Backbone.Model.extend({ 
initialize: function(aUrs){ … }, 
validate: function(aUrs){ 
if(aUrs.text.length < 1){ 
return ‘回复不能为空’; 
} 
} 
}); 
var comment = new Comment(); 
comment.set({text: ‘’},{ 
error: function(model, error){ 
alert(error); 
} 
});
What 
• 集合(Collection) 
o 模型的有序组合 
o Add,Remove,Fetch,Reset,Create,Sort
What 
var Comments = new Backbone.Collection.extend({ 
model: Comment, 
initialize: function(models, options){ 
} 
});
What 
[ 
{ 
id: 6378, 
text: “高富帅的设计”, 
created_at: “3小时前”, 
user: { 
id: ”sasaliu”, 
user_name_zh: “刘沙”, 
user_name_en: "ʺsasaliu"ʺ, 
small_avatar: "ʺ/data/photo/sp__201203291751346381.jpg"ʺ 
... 
} 
}, 
{...} 
{...} 
]
What 
• extend 
• model 
• constructor/initialize 
• models 
• toJSON 
• Underscore Methods(25) 
• get 
• getByCid 
• at 
• length 
• comparator 
• sort 
• pluck 
• url 
• parse 
Comments = Backbone.Collection.extend({ 
model: Comment, 
initialize: function(models, options){ 
this.url = “/comments”; 
}, 
comparator: function(model){ 
return model.get(“id”); 
} 
});
Add,Remove,Fetch,Reset,Create,Sort 
collection.create(aUributes, [options]) 
var Comments = new Comments([{…}]); 
Comments.create({text:”高富帅的设计”}); 
var comment = new Comment({ 
text: “高富帅的设计” 
}); 
comment.save(); 
Comments.add(comment);
What 
• 视图(View) 
o 一个逻辑的UI组件 
o 委托DOM事件 
o 负责实例化集合
What 
Comment 
Comments
App.Views.Comment = Backbone.View.extend({ 
className: 'ʹ comment-­‐‑item'ʹ, 
template: $('ʹ#comment-­‐‑item-­‐‑template'ʹ).html(), 
events: { 
"ʺmouseenter"ʺ: "ʺshowActions"ʺ, 
"ʺmouseleave"ʺ: "ʺhideActions"ʺ 
}, 
initialize: function(){ 
_.bindAll(this,'ʹrender'ʹ); 
this.model.bind('ʹchange'ʹ, this.render); 
}, 
render: function(){ 
$(this.el).html(_.template( this.template,this.model.toJSON())); 
$(this.el).aUr({ 
'ʹdata-­‐‑comment-­‐‑id'ʹ: this.model.id 
}); 
return this; 
}, 
showActions: function(e){ 
this.$('ʹ.reply'ʹ).show(); 
}, 
hideActions: function(e){ 
this.$('ʹ.reply'ʹ).hide(); 
} 
});
var view = new App.Views.Comment({ 
model: model 
}); 
$('ʹbody'ʹ).append(view.render().el);
What 
• 路由(Backbone.Router) 
o 将应用程序的状态和URL的哈希片段关联在一起 
o 根据路由规则,连接到指定的动作和事件
App.Router.page = Backbone.Router.extend({ 
routes: { 
“”: 
“index”, 
“help”: 
“help”, 
// #help 
“search/:query”:”search”, 
// #search/miyukizhang 
}, 
initialize: function(){ 
Backbone.history.start(); 
}, 
index: function(){ /* … */}, 
help: function(){ 
// … 
}, 
search: function(query){ 
// … 
} 
});
Router Data 
Source 
Model/Collection 
Template 
View
• 其他 
What Backbone.js 
o Backbone.history 
o Backbone.sync 
o Utility Function
提纲 
• Why 
• What 
• 案例 
• Questions
提纲 
• Why 
• What 
• 案例 
• Questions
Questions 
提问环节

Más contenido relacionado

La actualidad más candente

[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVCAlive Kuo
 
【前端Mvc】之豆瓣说实践
【前端Mvc】之豆瓣说实践【前端Mvc】之豆瓣说实践
【前端Mvc】之豆瓣说实践taobao.com
 
jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009Remy Sharp
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说Ting Lv
 
Write Less Do More
Write Less Do MoreWrite Less Do More
Write Less Do MoreRemy Sharp
 
JavaScript for Flex Devs
JavaScript for Flex DevsJavaScript for Flex Devs
JavaScript for Flex DevsAaronius
 
A Short Introduction To jQuery
A Short Introduction To jQueryA Short Introduction To jQuery
A Short Introduction To jQuerySudar Muthu
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery EssentialsMark Rackley
 
Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...Thinqloud
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuerymanugoel2003
 
WebApps e Frameworks Javascript
WebApps e Frameworks JavascriptWebApps e Frameworks Javascript
WebApps e Frameworks Javascriptmeet2Brains
 
jQuery Presentation
jQuery PresentationjQuery Presentation
jQuery PresentationRod Johnson
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutesSimon Willison
 
JavaScript and jQuery Basics
JavaScript and jQuery BasicsJavaScript and jQuery Basics
JavaScript and jQuery BasicsKaloyan Kosev
 
An in-depth look at jQuery UI
An in-depth look at jQuery UIAn in-depth look at jQuery UI
An in-depth look at jQuery UIPaul Bakaus
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginningAnis Ahmad
 

La actualidad más candente (20)

[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
 
【前端Mvc】之豆瓣说实践
【前端Mvc】之豆瓣说实践【前端Mvc】之豆瓣说实践
【前端Mvc】之豆瓣说实践
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
 
jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
 
Write Less Do More
Write Less Do MoreWrite Less Do More
Write Less Do More
 
JavaScript for Flex Devs
JavaScript for Flex DevsJavaScript for Flex Devs
JavaScript for Flex Devs
 
A Short Introduction To jQuery
A Short Introduction To jQueryA Short Introduction To jQuery
A Short Introduction To jQuery
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery Essentials
 
Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 
WebApps e Frameworks Javascript
WebApps e Frameworks JavascriptWebApps e Frameworks Javascript
WebApps e Frameworks Javascript
 
jQuery Presentation
jQuery PresentationjQuery Presentation
jQuery Presentation
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutes
 
JavaScript and jQuery Basics
JavaScript and jQuery BasicsJavaScript and jQuery Basics
JavaScript and jQuery Basics
 
jQuery
jQueryjQuery
jQuery
 
An in-depth look at jQuery UI
An in-depth look at jQuery UIAn in-depth look at jQuery UI
An in-depth look at jQuery UI
 
jQuery
jQueryjQuery
jQuery
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 

Destacado

Электронный киоск
Электронный киоскЭлектронный киоск
Электронный киоскSouren M
 
Tech school indonesia
Tech school indonesiaTech school indonesia
Tech school indonesiaIhwan Lukman
 
Презентация Mobile-info
Презентация Mobile-infoПрезентация Mobile-info
Презентация Mobile-infoSouren M
 
Презентация Асмо пресс. 2006 г.
Презентация Асмо пресс. 2006 г.Презентация Асмо пресс. 2006 г.
Презентация Асмо пресс. 2006 г.Souren M
 
Immigrant Citizens Survey: Key Findings by Thomas Huddleston
Immigrant Citizens Survey: Key Findings by Thomas HuddlestonImmigrant Citizens Survey: Key Findings by Thomas Huddleston
Immigrant Citizens Survey: Key Findings by Thomas HuddlestonTom Huddleston
 
Taller de computación básica
Taller de computación básicaTaller de computación básica
Taller de computación básicaProfesor víctor n
 
Presentasjon1om barnehage2
Presentasjon1om barnehage2Presentasjon1om barnehage2
Presentasjon1om barnehage2ansam1234
 
Respiration, etc
Respiration, etcRespiration, etc
Respiration, etcJaye
 
New microsoft office power point presentation
New microsoft office power point presentationNew microsoft office power point presentation
New microsoft office power point presentationحازم عجمى
 
Presentasjon1om barnehage2
Presentasjon1om barnehage2Presentasjon1om barnehage2
Presentasjon1om barnehage2ansam1234
 
移动端Web app开发
移动端Web app开发移动端Web app开发
移动端Web app开发Zhang Xiaoxue
 
给初学者的Html5教程
给初学者的Html5教程给初学者的Html5教程
给初学者的Html5教程Zhang Xiaoxue
 
The Engagement Effect Dig South
The Engagement Effect Dig SouthThe Engagement Effect Dig South
The Engagement Effect Dig SouthJohn E. Smith
 
Презентация Mobile-Asmo
Презентация Mobile-AsmoПрезентация Mobile-Asmo
Презентация Mobile-AsmoSouren M
 
How are you protecting your general anesthesia procedure patients from contam...
How are you protecting your general anesthesia procedure patients from contam...How are you protecting your general anesthesia procedure patients from contam...
How are you protecting your general anesthesia procedure patients from contam...Steve Koontz
 

Destacado (20)

Электронный киоск
Электронный киоскЭлектронный киоск
Электронный киоск
 
Tech school indonesia
Tech school indonesiaTech school indonesia
Tech school indonesia
 
Презентация Mobile-info
Презентация Mobile-infoПрезентация Mobile-info
Презентация Mobile-info
 
Презентация Асмо пресс. 2006 г.
Презентация Асмо пресс. 2006 г.Презентация Асмо пресс. 2006 г.
Презентация Асмо пресс. 2006 г.
 
Immigrant Citizens Survey: Key Findings by Thomas Huddleston
Immigrant Citizens Survey: Key Findings by Thomas HuddlestonImmigrant Citizens Survey: Key Findings by Thomas Huddleston
Immigrant Citizens Survey: Key Findings by Thomas Huddleston
 
Taller de computación básica
Taller de computación básicaTaller de computación básica
Taller de computación básica
 
Sinthia
SinthiaSinthia
Sinthia
 
Presentasjon1om barnehage2
Presentasjon1om barnehage2Presentasjon1om barnehage2
Presentasjon1om barnehage2
 
Respiration, etc
Respiration, etcRespiration, etc
Respiration, etc
 
Caja tema
Caja temaCaja tema
Caja tema
 
Caja tema
Caja temaCaja tema
Caja tema
 
New microsoft office power point presentation
New microsoft office power point presentationNew microsoft office power point presentation
New microsoft office power point presentation
 
Presentasjon1om barnehage2
Presentasjon1om barnehage2Presentasjon1om barnehage2
Presentasjon1om barnehage2
 
移动端Web app开发
移动端Web app开发移动端Web app开发
移动端Web app开发
 
给初学者的Html5教程
给初学者的Html5教程给初学者的Html5教程
给初学者的Html5教程
 
2 do grado
2 do grado2 do grado
2 do grado
 
The Engagement Effect Dig South
The Engagement Effect Dig SouthThe Engagement Effect Dig South
The Engagement Effect Dig South
 
MK: DP
MK: DPMK: DP
MK: DP
 
Презентация Mobile-Asmo
Презентация Mobile-AsmoПрезентация Mobile-Asmo
Презентация Mobile-Asmo
 
How are you protecting your general anesthesia procedure patients from contam...
How are you protecting your general anesthesia procedure patients from contam...How are you protecting your general anesthesia procedure patients from contam...
How are you protecting your general anesthesia procedure patients from contam...
 

Similar a 前端MVC之BackboneJS

Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
Backbonejs for beginners
Backbonejs for beginnersBackbonejs for beginners
Backbonejs for beginnersDivakar Gu
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)Doris Chen
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecturepostrational
 
Heroku pop-behind-the-sense
Heroku pop-behind-the-senseHeroku pop-behind-the-sense
Heroku pop-behind-the-senseBen Lin
 
How I Learned to Stop Worrying and Love jQuery (Jan 2013)
How I Learned to Stop Worrying and Love jQuery (Jan 2013)How I Learned to Stop Worrying and Love jQuery (Jan 2013)
How I Learned to Stop Worrying and Love jQuery (Jan 2013)David Giard
 
Client-side MVC with Backbone.js (reloaded)
Client-side MVC with Backbone.js (reloaded)Client-side MVC with Backbone.js (reloaded)
Client-side MVC with Backbone.js (reloaded)iloveigloo
 
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5Tieturi Oy
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldChristian Melchior
 
Styling components with JavaScript
Styling components with JavaScriptStyling components with JavaScript
Styling components with JavaScriptbensmithett
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)Igor Bronovskyy
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksHjörtur Hilmarsson
 
JavaScript front end performance optimizations
JavaScript front end performance optimizationsJavaScript front end performance optimizations
JavaScript front end performance optimizationsChris Love
 
Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012
Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012
Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012crokitta
 
Plone Interactivity
Plone InteractivityPlone Interactivity
Plone InteractivityEric Steele
 

Similar a 前端MVC之BackboneJS (20)

Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
Backbonejs for beginners
Backbonejs for beginnersBackbonejs for beginners
Backbonejs for beginners
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecture
 
Heroku pop-behind-the-sense
Heroku pop-behind-the-senseHeroku pop-behind-the-sense
Heroku pop-behind-the-sense
 
How I Learned to Stop Worrying and Love jQuery (Jan 2013)
How I Learned to Stop Worrying and Love jQuery (Jan 2013)How I Learned to Stop Worrying and Love jQuery (Jan 2013)
How I Learned to Stop Worrying and Love jQuery (Jan 2013)
 
Client-side MVC with Backbone.js (reloaded)
Client-side MVC with Backbone.js (reloaded)Client-side MVC with Backbone.js (reloaded)
Client-side MVC with Backbone.js (reloaded)
 
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected World
 
Styling components with JavaScript
Styling components with JavaScriptStyling components with JavaScript
Styling components with JavaScript
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & Tricks
 
Wt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technologyWt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technology
 
Wt unit 2 ppts client side technology
Wt unit 2 ppts client side technologyWt unit 2 ppts client side technology
Wt unit 2 ppts client side technology
 
Backbone js
Backbone jsBackbone js
Backbone js
 
JavaScript front end performance optimizations
JavaScript front end performance optimizationsJavaScript front end performance optimizations
JavaScript front end performance optimizations
 
Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012
Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012
Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012
 
Symfony2 and AngularJS
Symfony2 and AngularJSSymfony2 and AngularJS
Symfony2 and AngularJS
 
Plone Interactivity
Plone InteractivityPlone Interactivity
Plone Interactivity
 

Último

Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 

Último (20)

Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 

前端MVC之BackboneJS

  • 2. 提纲 • Why • What • 案例 • Questions
  • 3. 提纲 • Why • What • 案例 • Questions
  • 4. Why • JS开发现状: 1. 数据和视图耦合过紧 var list = “”; $.each (data, function(index. value){ list += “<li id=‘item-­‐‑” + value.Id + “’>” + value.Name + “</li>”; }); $(“ul”).append(list);
  • 5. Why 2. 回调过多 $.getJSON(“/Items”, function(data){ var list = “”; $.each(data, function(index, value){ list += “<li id=‘item-­‐‑” + value.Id + “’>” + value.Name + “</li>”; }); $(“ul”).append(list); $(“li”).click(function(){ var $this = $(this); var id = $this.aUr(“id”).replace(“items-­‐‑”, “”); $.post(“/Items”, {id: id}, function(){ $this.fadeOut(function(){ $this.remove(); }); }); }); });
  • 6. Why • 遇到的问题: o 程序结构不清晰,不利于理解 o 大量的字符串拼接 o 大量的回调函数 o 难以维护
  • 7. Why • 现代Web App的特点: o 页面不整体刷新 o 与服务器的交互均由Ajax完成 o 服务器只负责提供数据接口 o 逻辑、展现、行为都交给JavaScript处理 o 速度更快、体验更好
  • 8. Why • 遇到的问题: o JS开发量大、逻辑复杂 o 如果整个App只有一个URL,不便于收藏和传播 o 无浏览器历史记录,浏览器前进后退按钮失效 o 对搜索引擎不友好
  • 9. Why • So,我们需要一个解决方案: o 使程序结构清晰、便于理解 o 将数据与UI解耦 o 不存在回调函数 o 减少重复劳动 o 易于维护和扩展
  • 10. Why • So,我们需要一个解决方案(更实际地): o 基于数据层的RESTful Web服务 o 事件(数据与UI解耦) o 一个牢固的路由系统 o 一个模板引擎 o 一个可以解决上面所有需求轻量JavaScript框架
  • 12. 提纲 • Why • What • 案例 • Questions
  • 13. What Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
  • 14. What Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
  • 15. What Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
  • 16. What Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
  • 17. What Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
  • 18. What • 依赖: o Underscore.js o jQuery 或者 Zepto o Json2.js
  • 20. What MVC Model / Collection 数据(模型)
  • 21. What MVC Model / Collection 数据(模型) Template 展现层(视图)
  • 22. What MVC Model / Collection 数据(模型) Template 展现层(视图) View 控制器
  • 23. What MVC Model / Collection 数据(模型) Template 展现层(视图) View 控制器 Router ???
  • 24. What MVC Model / Collection 数据(模型) Template 展现层(视图) View 控制器 Router ??? Controller
  • 25. What • 模型(Model) o 用来存放应用的所有数据对象 o 能够被创建、验证和销毁等 o 属性的改变会触发“change”事件
  • 26. What 模型 • Fetch HTTP GET /url • Save(new) HTTP POST /url • Save HTTP PUT /url/id • Destroy HTTP DELETE /url/id
  • 27. What var Comment = Backbone.Model.extend(); var comment = new Comment({ id: 6378, text: “高富帅的设计”, created_at: “3小时前”, user: { id: ”sasaliu”, user_name_zh: “刘沙” } });
  • 28. • extend • constructor/initialize • get • set • escape • has • unset • clear • id • cid • attributes • defaults • toJSON comment.get(‘text’ ); //高富帅的设计 comment.set( {‘text’:”<script>console.log(‘xss’)</script>”}, {silent: true} ); comment.escape(‘text’);// &lt;script&gt;console.log(&#x27xss&#x27)&lt;&#x2F; script&gt; comment.has(‘city’ );//false comment.unset(‘text’); //触发’change’事件 var Comment = new Backbone.Model.extend({ //hash or function() defaults: { ‘root’: ‘tea.cdc.com’ }, initialize: function(){…} }); var comment = new Comment(); comment.get(‘root’); //’tea.cdc.com’
  • 29. • fetch • save • desrtoy • validate • url • urlRoot • parse • clone • isNew • change • hasChanged • changedAttributes • previous • previousAttributes var Comment = new Backbone.Model.extend({ urlRoot: ‘/comments’, initialize: function(aUrs){ … } }); var comment = new Comment({id: 123456}); comment.url(); // ‘/comments/123456’ comment.fetch(); var Comment = new Backbone.Model.extend({ initialize: function(aUrs){ … }, validate: function(aUrs){ if(aUrs.text.length < 1){ return ‘回复不能为空’; } } }); var comment = new Comment(); comment.set({text: ‘’},{ error: function(model, error){ alert(error); } });
  • 30. What • 集合(Collection) o 模型的有序组合 o Add,Remove,Fetch,Reset,Create,Sort
  • 31. What var Comments = new Backbone.Collection.extend({ model: Comment, initialize: function(models, options){ } });
  • 32. What [ { id: 6378, text: “高富帅的设计”, created_at: “3小时前”, user: { id: ”sasaliu”, user_name_zh: “刘沙”, user_name_en: "ʺsasaliu"ʺ, small_avatar: "ʺ/data/photo/sp__201203291751346381.jpg"ʺ ... } }, {...} {...} ]
  • 33. What • extend • model • constructor/initialize • models • toJSON • Underscore Methods(25) • get • getByCid • at • length • comparator • sort • pluck • url • parse Comments = Backbone.Collection.extend({ model: Comment, initialize: function(models, options){ this.url = “/comments”; }, comparator: function(model){ return model.get(“id”); } });
  • 34. Add,Remove,Fetch,Reset,Create,Sort collection.create(aUributes, [options]) var Comments = new Comments([{…}]); Comments.create({text:”高富帅的设计”}); var comment = new Comment({ text: “高富帅的设计” }); comment.save(); Comments.add(comment);
  • 35. What • 视图(View) o 一个逻辑的UI组件 o 委托DOM事件 o 负责实例化集合
  • 37.
  • 38. App.Views.Comment = Backbone.View.extend({ className: 'ʹ comment-­‐‑item'ʹ, template: $('ʹ#comment-­‐‑item-­‐‑template'ʹ).html(), events: { "ʺmouseenter"ʺ: "ʺshowActions"ʺ, "ʺmouseleave"ʺ: "ʺhideActions"ʺ }, initialize: function(){ _.bindAll(this,'ʹrender'ʹ); this.model.bind('ʹchange'ʹ, this.render); }, render: function(){ $(this.el).html(_.template( this.template,this.model.toJSON())); $(this.el).aUr({ 'ʹdata-­‐‑comment-­‐‑id'ʹ: this.model.id }); return this; }, showActions: function(e){ this.$('ʹ.reply'ʹ).show(); }, hideActions: function(e){ this.$('ʹ.reply'ʹ).hide(); } });
  • 39. var view = new App.Views.Comment({ model: model }); $('ʹbody'ʹ).append(view.render().el);
  • 40. What • 路由(Backbone.Router) o 将应用程序的状态和URL的哈希片段关联在一起 o 根据路由规则,连接到指定的动作和事件
  • 41. App.Router.page = Backbone.Router.extend({ routes: { “”: “index”, “help”: “help”, // #help “search/:query”:”search”, // #search/miyukizhang }, initialize: function(){ Backbone.history.start(); }, index: function(){ /* … */}, help: function(){ // … }, search: function(query){ // … } });
  • 42. Router Data Source Model/Collection Template View
  • 43. • 其他 What Backbone.js o Backbone.history o Backbone.sync o Utility Function
  • 44. 提纲 • Why • What • 案例 • Questions
  • 45.
  • 46. 提纲 • Why • What • 案例 • Questions