SlideShare ist ein Scribd-Unternehmen logo
1 von 61
Downloaden Sie, um offline zu lesen
Mokoversity 
Backbone & MVW 101 
2014.8.20 
Jollen Chen 
<jollen@jollen.org> 
www.mokoversity.com
Mokoversity 
為什麼需要 Backbone.js ?
Single Page Web Apps 
Source: http://apievangelist.com/2013/05/23/ember-angular-backbone-single-page- 
applications-and-apis/
Through a RESTful API 
Source: http://cyberasylum.janithw.com/tag/single-paged-applications/
MVC for Client 
Simple MVC framework ⾄至少要能將 Code 與 View 
分開。View ⼜又包含 Presentation 與 UI。 
http://blog.oscarliang.net/simple-mvc-framework-tutorial-part-2/
SPAs and RESTful 
It’s difficult to build Single Page Applications that 
by simply using jQuery or MooTools. They don’t 
have formal structure. 
The browser is no longer the only client, we now 
have mobile devices, tablet devices, Google 
Goggles and electronic fridges etc. 
Single-page web apps are the future. Backbone.js 
is essentially MVC for the client and allows you 
to make your code modular. 
http://backbonetutorials.com/why-would-you-use-backbone/
URL Router 
Source: http://msdn.microsoft.com/en-us/magazine/hh288078.aspx
Mokoversity 
MVC, MVP 與 MVVM 觀念介紹
URL Router 
Source: http://khatrishashank.wordpress.com/2013/10/11/a-comparison-of-architectural- 
patternsmvvm-and-mvc/
MVVM 
Source: http://khatrishashank.wordpress.com/2013/10/11/a-comparison-of-architectural- 
patternsmvvm-and-mvc/
Source: http://khatrishashank.wordpress.com/2013/10/11/a-comparison-of-architectural- 
patternsmvvm-and-mvc/
MVC vs MVVM 
MVC MVVM 
寫程式不⽤用寫程式 
Template + 
Control Logic 
Template + 
Data Binding
MVC vs MVP 
MVC MVP 
Controller 處理 
User Inputs 
View 處理 
User Inputs 
Controller uses 
Presentation 
Model 
Controller is 
Presentation 
Model
MVVM 
Source: http://mvcsharp.org/Overview/Default.aspx
MV* - Whatever 
寫的好就是 MVP,寫不好就是 MVC;神⼈人級寫出來就是 
MVVM。連 MVC 都沒有的是幼幼班。 
Source: http://www.ace-dnn.com/knowledge-base/implementation-of-mvvm-design- 
pattern-in-dnn.aspx
Mokoversity 
TicTacToe
MVC 初體驗 
• 將以⼀一個 TicTacToe 遊戲的實作: 
• 了解 MVC 的重點性 
• MVC 的基本實作觀念
REST 與 JSON 
• 將 REST API 回傳的 JSON 資料,轉換成 
HTML5 標籤,並顯⽰示在 UI 上 
• 使⽤用 jQuery AJAX 呼叫 REST API 是⽐比較 
Dirty 的⽅方式 
• 須導⼊入 MVC 的框架
Key-Value Pairs 
• JSON 資料格式 
• 將 JSON「套⽤用」到 Template 
{ "name": "jollen"}
使⽤用 AJAX 呼叫 REST API 
// 等候 HTML ⽂文件完成載⼊入! 
$(document).ready(function(){! 
! initSubmitForm();! 
});! 
! 
var initSubmitForm = function() {! 
// 使⽤用 ajax() 來呼叫 REST API! 
$.ajax({! 
url: 'http://localhost:3000/discussion/latest/3',! 
type: "GET",! 
dataType: "json",! 
complete: function(data, textStatus, jqXHR) {! 
console.log(textStatus);! 
},! 
success: function (data, textStatus, jqXHR) {! 
console.log(data);! 
}! 
});! 
! 
return false;! 
};
沒有 MVC 架構 
• 典型沒有 MVC 架構的寫法 
var dataMapping = function(data) {! 
for (i = 0; i < data.length; i++) {! 
var htmlCode = ! 
"<div class="alert alert-dismissable alert-info">"! 
+ " <button type="button" class="close" data-dismiss=" 
alert" aria-hidden="true">×</button>"! 
+ " <h4>jollen</h4>"! 
+ data[i].message! 
+"</div>";! 
! 
$('#message').append(htmlCode);! 
}! 
}
關於 RESTful 
• 現代的 Web App 開發,以 REST API 的⽅方式 
整合 Client(Device)與 Server 
• RESTful 是 Web Service 主流架構 
• RESTful 易於 Web Service 與不同裝置的整 
合,例如:Desktop、Phone、Tablet 與 
TV 等
安裝 Underscore 與 Backbone 
• Step 1:安裝 Underscore 與 Backbone 
• http://underscorejs.org/underscore-min.js 
• http://backbonejs.org/backbone-min.js 
• 存放⾄至 nodejs-chat 專案的 client/ 
javascripts/ ⺫⽬目錄下 
• Backbone 必須與 Underscore 搭配使⽤用。
建⽴立主要⾴頁⾯面 
• Step 2:修改 chat.html 
• 順序不能改變,先引⼊入 Underscore 後, 
再引⼊入 Backbone 
• Backbone 是⼀一個 MVC 框架,其中 View 
的部份由 Underscore ⽀支援 
<script type='text/javascript' src="javascripts/underscore-min.js"></script>! 
<script type='text/javascript' src="javascripts/backbone-min.js"></script>
撰寫基本的 Backbone 框架 
• Step 3:重新 
撰寫 client/ 
javascripts/ 
app.js 
/**! 
* SETUP! 
**/! 
var app = app || {};! 
! 
/**! 
* MODELS! 
**/! 
!! 
/**! 
* VIEWS! 
**/! 
app.MessageView = Backbone.View.extend({! 
events: {! 
},! 
});! 
! 
/**! 
* BOOTUP! 
**/! 
$(document).ready(function() {! 
app.messageView = new app.MessageView();! 
});
Backbone 初體驗 
• Backbone 是⼀一個 MVC (MVW) 框架,⼀一開始先 
定義 Model 與 View 
• Model 就是「表⽰示資料的模型」,也就是將會顯 
⽰示在畫⾯面上的資料 
• View 的部份將負責處理 Template 與 Model 的 
對應,必須先了解 Key-Value Paris 觀念 
• View 的部份,也負責處理控制的部份,例如: 
Button 的 click 事件
Backbone 的事件處理 
• Step 4:Backbone.View 事件處理 
• 為這個區塊加⼊入名字 
! <div class="row" id="message-save">! 
! ! <div class="col-md-9">! 
! ! ! <input class="form-control" type="text" name="message">! 
! ! </div>! 
! ! <div class="col-md-3">! 
! ! ! <button class="btn btn-large btn-primary btn-message-save">送出</ 
button>! 
! ! </div>! 
! </div>
實作 Backbone 事件處理 
• 使⽤用 events 屬性 
1 app.MessageView = Backbone.View.extend({! 
2 el: '#message-save',! 
3 events: {! 
4 'click .btn-message-save': 'save'! 
5 },! 
6 save: function() {! 
7 alert("Saving...");! 
8 }! 
9 });
Mokoversity 
MV Whatever
Work with Front-End Developers 
Use MVC, MVP and MVVM 
Call REST API in Backbone way 
Customizable CSS 
CSS generation and minify
Model, View and Control 
Views and Templating 
Handlebars.js and Underscore’s 
template 
http://addyosmani.com/resources/essentialjsdesignpatterns/book/#jquerypluginpatterns
Model, View and Control 
Spine.js and Backbone.js
Model, View and Control 
manage the data for an application 
e.g. Backbone "collections"
MPV 
Models, Views & Presenters 
MVP is generally used most often in 
enterprise-level applications where it's 
necessary to reuse as much 
presentation logic as possible. 
http://addyosmani.com/resources/essentialjsdesignpatterns/book/#jquerypluginpatterns
Model View ViewModel 
an architectural pattern based on MVC 
and MVP, 
! 
which attempts to more clearly 
separate the development of user-interfaces 
(UI) from that of the business 
logic and behavior in an application. 
http://addyosmani.com/resources/essentialjsdesignpatterns/book/#jquerypluginpatterns
Mokoversity 
View and Model
認識 View.$el 
• A cached jQuery object for the 
view's element. 
• ⼀一個 jQuery 物件 
var message = $('input[name="message"]').val(); 
var message = this.$el.find('input[name="message"]').val();!
認識 this 物件 
• this 是⼀一個物件,代表「這個 View」的意思 
• this 為 Backbone.View 類別
this.$el 與 $ 
• 使⽤用 *this.$el* ⽽而不是直接使⽤用 *$* 物件 
• 為了避免不必要的 DOM 操作 
• 將把 *$.ajax* 的做法,以 Model 的⽅方式取 
代
認識 Backbone.Model 
• Backbone.Model ⽤用來表⽰示(存放)資料 
• ⼀一個「資料模型」的類別
使⽤用 Backbone.Model 
• 修改 client/javascripts/app.js 
1 app.Message = Backbone.Model.extend({ ! 
2 defaults: {! 
3 success: false,! 
4 errors: [],! 
5 errfor: {},! 
6! 
7 message: 'No message yet.'! 
8 }! 
9 });
使⽤用 Underscore 
• Frontend Template 系統 
• 宣告 Template: 
<script type='text/template' id='tmpl-message'>! 
! <div class="alert alert-dismissable alert-info">! 
! ! <button type="button" class="close" data-dismiss="alert" aria-hidden=" 
true">! 
! ! ! ×</button>! 
! ! <h4>jollen</h4>! 
! ! <%= message %>! 
! </div>! 
</script>
使⽤用 Underscore 注意事項 
• "type" 必須定義為 "text/template" 
• 給予⼀一個名字,上述範例將 Template 命名 
為 "tmpl-message" 
• 使⽤用 <%= *variable-name* => 來取⽤用變 
數值,變數名稱在上述的 Model 裡定義, 
Underscore 會將 Model 的變數與 
Template 做對應,並且⽤用變數值取代
Underscore 觀念⼩小結 
• ViewModel:這個對應關係就是 ViewModel 的觀念 
• Key-Value Pairs:Model 裡的資料,要⽤用 Key-Value 
Pairs 的格式表⽰示,JSON 就是 Key-Value Pairs 的格式 
• Template:將 Model 裡的資料,顯⽰示到畫⾯面上,是透 
過 Template,並且是由 Underscore 來完成 
• Code Ignorance:如上,顯⽰示資料到畫⾯面上,不需要寫 
程式;對設計師來說,只要修改 Template 即可,不會 
有程式碼的困擾
View 與 Controller 
• View 與 Controller 的 Binding 
• Code Ignorance-ViewModel 
1 initialize: function() {! 
2 this.model = new app.Message();! 
3 this.template = _.template($('#tmpl-message').html());! 
4! 
5 this.model.bind('change', this.render, this);! 
6 this.render();! 
7 }
View Binding 說明 
• 實例化 View 時,constructor 與 initialize 
會被叫 
• 實作 initialize 函數來加⼊入 Model 
• 將 Model 的實例化存放到 View.model 裡
Backbone 與 Underscore 
• 在 Backbone.View 裡定義⼀一個 template 函數 
• 採⽤用的 Template 系統是 Underscore 
• 為 Backbone.View 定義想要使⽤用的 Template 系統 
• 如何讓 Backbone.View 使⽤用 Underscore 做 
為 Template 系統呢? 
• 將 Backbone.View.template 定義為 _.template() 即 
可
使⽤用 Underscore 
• _ 是 Underscore 的物件 
• Underscore 名稱的由來 
• 將取得的 Template 傳給 
*_.template* 即可 
this.template = _.template($('#tmpl-message').html());
實作 render() 函數 
• 在 View 裡實作 render() 函數 
• render() 會將 Model 與 Template 
做對應,對應後的結果就是⼀一份 
HTML5 ⽂文件 
render: function() {! 
var data = this.template(this.model.attributes);! 
! 
this.$el.find('#message').html(data);! 
return this;! 
},
render() 實作說明 
• 先呼叫 this.template 函數,這個函數已經被定義為 
Underscore Template 系統 
• this.model.attributes 存放的是「Model State」 
• Model State 就是 Model ⺫⽬目前所存放的資料;資料會以 JSON 的格式表 
⽰示。 
• this.model.attributes 存放了 Model Data,並且是 JSON 格式 
• 將 Data 交給 Template 系統去做 Data Mapping。這⾏行程式 
碼是 ViewModel 觀念的靈魂。 
• 最後將 Template 系統處理好的 HTML5 ⽂文件,放到想顯⽰示的 
網⾴頁位置即可
Mokoversity 
Invoke RESTful API
呼叫 REST API:AJAX ⽅方式 
app.MessageView = Backbone.View.extend({! 
el: '#message-save',! 
events: {! 
'click .btn-message-save': 'save'! 
},! 
save: function() {! 
var message = $('input[name="message"]').val();! 
! 
$.ajax({! 
url: '/discussion/' + message,! 
type: 'POST',! 
dataType: "json",! 
success: function (data, textStatus, jqXHR) {! 
alert("已儲存成功");! 
},! 
complete: function (data, textStatus, jqXHR) {! 
}! 
});! 
}! 
});
關於 Backbone Data Model 
• Backbone.Model 除了表⽰示資料外,還提供 
各種處理模型 
• 最重要的處理模型:manage changee 
• ⼀一但 Model 裡的資料有變動(例如:新增、 
刪除等),就要重新做 "Data Mapping" 
• Backbone Way 的處理⽅方式,是透過 
Backbone.Model.fetch
使⽤用 Backbone Data Model 的理由 
• 使⽤用 *$.ajax() 來呼叫 REST API 雖然是可⾏行 
的做法,但是有⼀一個缺點:處理 Response 
data 的架構不夠嚴謹 
• 使⽤用 *$.ajax() 來呼叫 REST API 時,是直接 
把 API 當做 *ajax() 的參數,這個做法有⼀一 
個缺點:API 與 Response data 是⼀一種⽐比較 
鬆散的關係
Backbone Data Model 優點 
• 使⽤用 Model fetch 的⽅方式,讓 Response 
data 的處理更嚴謹 
• 使⽤用 Data model 的⽅方式,,讓 Data 與 
API 偶和(Aggregation)在⼀一起
使⽤用 Backbone.Model.fetch 
this.model.fetch({! 
success: function(model, response, options) {! 
}! 
});
修改 Model 
• Backbone.Model.fetch 根據 
this.model 裡的 url 定義,來呼叫 
REST API 
app.Message = Backbone.Model.extend({! 
url: '/discussion/latest/5',! 
defaults: {! 
success: false,! 
errors: [],! 
errfor: {},! 
! 
message: 'No message yet.',! 
messages: []! 
}! 
});
設定 Data Model 
• 呼叫 Backbone.Model.fetch 後, 
Backbone 會幫我們呼叫 REST API,並且取 
得 Response data 
• 成功取得 Response data, 
Backbone.Model.fetch 就會 Callback 
success 函數。
關於 Data State 的變化 
• self.model.set 的意思是,將取得的 
response data 儲存到 Data model裡 
• 由於 Data model 有了變動,所以 
Backbone 便會呼叫 render() 函數 
• 在 render() 函數裡,再 Render 出新的內容
觀念⼩小結 
• 透過 Data model 整合 REST API,以及 
Response data 
• 將 REST API 與 Response data 封裝成 
Data model 
• 在 Data model 變動時,重新 Render 畫⾯面
使⽤用 Backbone.Collection 
app.PostCollection = Backbone.Collection.extend({! 
! model: app.Post! 
});!

Weitere ähnliche Inhalte

Was ist angesagt?

运维系统开发与Rails 3页面开发实践
运维系统开发与Rails 3页面开发实践运维系统开发与Rails 3页面开发实践
运维系统开发与Rails 3页面开发实践Li JianYe
 
JQuery 学习
JQuery 学习JQuery 学习
JQuery 学习cssrain
 
不断归零的前端人生 - 2016 中国软件开发者大会
不断归零的前端人生 - 2016 中国软件开发者大会不断归零的前端人生 - 2016 中国软件开发者大会
不断归零的前端人生 - 2016 中国软件开发者大会Joseph Chiang
 
JQuery Mobile 框架介紹與使用 20140713
JQuery Mobile 框架介紹與使用 20140713JQuery Mobile 框架介紹與使用 20140713
JQuery Mobile 框架介紹與使用 20140713EZoApp
 
Servlet & JSP 教學手冊第二版 - 第 9 章:整合資料庫
Servlet & JSP 教學手冊第二版 - 第 9 章:整合資料庫Servlet & JSP 教學手冊第二版 - 第 9 章:整合資料庫
Servlet & JSP 教學手冊第二版 - 第 9 章:整合資料庫Justin Lin
 
前端MVC之backbone
前端MVC之backbone前端MVC之backbone
前端MVC之backboneJerry Xie
 
浅析浏览器解析和渲染
浅析浏览器解析和渲染浅析浏览器解析和渲染
浅析浏览器解析和渲染Ailsa126
 
旺铺前端设计和实现
旺铺前端设计和实现旺铺前端设计和实现
旺铺前端设计和实现hua qiu
 
jQuery 選取器解析
jQuery 選取器解析jQuery 選取器解析
jQuery 選取器解析Kingsley Zheng
 
Jquery指南
Jquery指南Jquery指南
Jquery指南yiditushe
 

Was ist angesagt? (12)

运维系统开发与Rails 3页面开发实践
运维系统开发与Rails 3页面开发实践运维系统开发与Rails 3页面开发实践
运维系统开发与Rails 3页面开发实践
 
JQuery 学习
JQuery 学习JQuery 学习
JQuery 学习
 
J query
J queryJ query
J query
 
Javascript
JavascriptJavascript
Javascript
 
不断归零的前端人生 - 2016 中国软件开发者大会
不断归零的前端人生 - 2016 中国软件开发者大会不断归零的前端人生 - 2016 中国软件开发者大会
不断归零的前端人生 - 2016 中国软件开发者大会
 
JQuery Mobile 框架介紹與使用 20140713
JQuery Mobile 框架介紹與使用 20140713JQuery Mobile 框架介紹與使用 20140713
JQuery Mobile 框架介紹與使用 20140713
 
Servlet & JSP 教學手冊第二版 - 第 9 章:整合資料庫
Servlet & JSP 教學手冊第二版 - 第 9 章:整合資料庫Servlet & JSP 教學手冊第二版 - 第 9 章:整合資料庫
Servlet & JSP 教學手冊第二版 - 第 9 章:整合資料庫
 
前端MVC之backbone
前端MVC之backbone前端MVC之backbone
前端MVC之backbone
 
浅析浏览器解析和渲染
浅析浏览器解析和渲染浅析浏览器解析和渲染
浅析浏览器解析和渲染
 
旺铺前端设计和实现
旺铺前端设计和实现旺铺前端设计和实现
旺铺前端设计和实现
 
jQuery 選取器解析
jQuery 選取器解析jQuery 選取器解析
jQuery 選取器解析
 
Jquery指南
Jquery指南Jquery指南
Jquery指南
 

Andere mochten auch

Mokoversity Course: Apple Swift 101 - Introduction
Mokoversity Course: Apple Swift 101 - IntroductionMokoversity Course: Apple Swift 101 - Introduction
Mokoversity Course: Apple Swift 101 - IntroductionJollen Chen
 
WoT.City and IoT Protocols Movement @ Taipei, Taiwan
WoT.City and IoT Protocols Movement @ Taipei, TaiwanWoT.City and IoT Protocols Movement @ Taipei, Taiwan
WoT.City and IoT Protocols Movement @ Taipei, TaiwanJollen Chen
 
MongoDB & NoSQL 101
 MongoDB & NoSQL 101 MongoDB & NoSQL 101
MongoDB & NoSQL 101Jollen Chen
 
IoT and Maker Crossover (IMCO) Conference 2015
IoT and Maker Crossover (IMCO) Conference 2015IoT and Maker Crossover (IMCO) Conference 2015
IoT and Maker Crossover (IMCO) Conference 2015Jollen Chen
 
Single-Page Application Design Principles 101
Single-Page Application Design Principles 101Single-Page Application Design Principles 101
Single-Page Application Design Principles 101Jollen Chen
 
Maker of Things - the open IoT cloud for makers chapter.
Maker of Things - the open IoT cloud for makers chapter.Maker of Things - the open IoT cloud for makers chapter.
Maker of Things - the open IoT cloud for makers chapter.Jollen Chen
 

Andere mochten auch (6)

Mokoversity Course: Apple Swift 101 - Introduction
Mokoversity Course: Apple Swift 101 - IntroductionMokoversity Course: Apple Swift 101 - Introduction
Mokoversity Course: Apple Swift 101 - Introduction
 
WoT.City and IoT Protocols Movement @ Taipei, Taiwan
WoT.City and IoT Protocols Movement @ Taipei, TaiwanWoT.City and IoT Protocols Movement @ Taipei, Taiwan
WoT.City and IoT Protocols Movement @ Taipei, Taiwan
 
MongoDB & NoSQL 101
 MongoDB & NoSQL 101 MongoDB & NoSQL 101
MongoDB & NoSQL 101
 
IoT and Maker Crossover (IMCO) Conference 2015
IoT and Maker Crossover (IMCO) Conference 2015IoT and Maker Crossover (IMCO) Conference 2015
IoT and Maker Crossover (IMCO) Conference 2015
 
Single-Page Application Design Principles 101
Single-Page Application Design Principles 101Single-Page Application Design Principles 101
Single-Page Application Design Principles 101
 
Maker of Things - the open IoT cloud for makers chapter.
Maker of Things - the open IoT cloud for makers chapter.Maker of Things - the open IoT cloud for makers chapter.
Maker of Things - the open IoT cloud for makers chapter.
 

Ähnlich wie Backbone.js and MVW 101

Html5和css3入门
Html5和css3入门Html5和css3入门
Html5和css3入门Xiujun Ma
 
HTML5概览
HTML5概览HTML5概览
HTML5概览Adam Lu
 
Script with engine
Script with engineScript with engine
Script with engineWebrebuild
 
從 Web Site 到 Web Application,從 Web Services 到 Mobile Services
從 Web Site 到 Web Application,從 Web Services 到 Mobile Services從 Web Site 到 Web Application,從 Web Services 到 Mobile Services
從 Web Site 到 Web Application,從 Web Services 到 Mobile ServicesKuo-Chun Su
 
淘宝移动端Web开发最佳实践
淘宝移动端Web开发最佳实践淘宝移动端Web开发最佳实践
淘宝移动端Web开发最佳实践Du Yamin
 
淘宝移动端Web开发最佳实践
淘宝移动端Web开发最佳实践淘宝移动端Web开发最佳实践
淘宝移动端Web开发最佳实践jay li
 
Spring 2.x 中文
Spring 2.x 中文Spring 2.x 中文
Spring 2.x 中文Guo Albert
 
2011 JavaTwo JSF 2.0
2011 JavaTwo JSF 2.02011 JavaTwo JSF 2.0
2011 JavaTwo JSF 2.0Anthony Chen
 
J engine -构建高性能、可监控的前端应用框架
J engine -构建高性能、可监控的前端应用框架J engine -构建高性能、可监控的前端应用框架
J engine -构建高性能、可监控的前端应用框架fangdeng
 
J engine -构建高性能、可监控的前端应用框架
J engine -构建高性能、可监控的前端应用框架J engine -构建高性能、可监控的前端应用框架
J engine -构建高性能、可监控的前端应用框架wtxidian
 
Struts+Spring+Hibernate整合教程
Struts+Spring+Hibernate整合教程Struts+Spring+Hibernate整合教程
Struts+Spring+Hibernate整合教程yiditushe
 
Struts+Spring+Hibernate整合教程
Struts+Spring+Hibernate整合教程Struts+Spring+Hibernate整合教程
Struts+Spring+Hibernate整合教程appollo0312
 
JdonFramework中文
JdonFramework中文JdonFramework中文
JdonFramework中文banq jdon
 
使用kslite支持第三方内容开发
使用kslite支持第三方内容开发使用kslite支持第三方内容开发
使用kslite支持第三方内容开发leneli
 
利用Signalr打造即時通訊@Tech day geek
利用Signalr打造即時通訊@Tech day geek利用Signalr打造即時通訊@Tech day geek
利用Signalr打造即時通訊@Tech day geekJohnson Gau
 
Real World ASP.NET MVC
Real World ASP.NET MVCReal World ASP.NET MVC
Real World ASP.NET MVCjeffz
 
非常靠谱 Html 5
非常靠谱 Html 5 非常靠谱 Html 5
非常靠谱 Html 5 Tony Deng
 

Ähnlich wie Backbone.js and MVW 101 (20)

Html5和css3入门
Html5和css3入门Html5和css3入门
Html5和css3入门
 
HTML5概览
HTML5概览HTML5概览
HTML5概览
 
Script with engine
Script with engineScript with engine
Script with engine
 
從 Web Site 到 Web Application,從 Web Services 到 Mobile Services
從 Web Site 到 Web Application,從 Web Services 到 Mobile Services從 Web Site 到 Web Application,從 Web Services 到 Mobile Services
從 Web Site 到 Web Application,從 Web Services 到 Mobile Services
 
淘宝移动端Web开发最佳实践
淘宝移动端Web开发最佳实践淘宝移动端Web开发最佳实践
淘宝移动端Web开发最佳实践
 
淘宝移动端Web开发最佳实践
淘宝移动端Web开发最佳实践淘宝移动端Web开发最佳实践
淘宝移动端Web开发最佳实践
 
Spring 2.x 中文
Spring 2.x 中文Spring 2.x 中文
Spring 2.x 中文
 
CRUD 綜合運用
CRUD 綜合運用CRUD 綜合運用
CRUD 綜合運用
 
2011 JavaTwo JSF 2.0
2011 JavaTwo JSF 2.02011 JavaTwo JSF 2.0
2011 JavaTwo JSF 2.0
 
J engine -构建高性能、可监控的前端应用框架
J engine -构建高性能、可监控的前端应用框架J engine -构建高性能、可监控的前端应用框架
J engine -构建高性能、可监控的前端应用框架
 
J engine -构建高性能、可监控的前端应用框架
J engine -构建高性能、可监控的前端应用框架J engine -构建高性能、可监控的前端应用框架
J engine -构建高性能、可监控的前端应用框架
 
Struts+Spring+Hibernate整合教程
Struts+Spring+Hibernate整合教程Struts+Spring+Hibernate整合教程
Struts+Spring+Hibernate整合教程
 
Struts+Spring+Hibernate整合教程
Struts+Spring+Hibernate整合教程Struts+Spring+Hibernate整合教程
Struts+Spring+Hibernate整合教程
 
JdonFramework中文
JdonFramework中文JdonFramework中文
JdonFramework中文
 
Web base 吴志华
Web base 吴志华Web base 吴志华
Web base 吴志华
 
Mvc
MvcMvc
Mvc
 
使用kslite支持第三方内容开发
使用kslite支持第三方内容开发使用kslite支持第三方内容开发
使用kslite支持第三方内容开发
 
利用Signalr打造即時通訊@Tech day geek
利用Signalr打造即時通訊@Tech day geek利用Signalr打造即時通訊@Tech day geek
利用Signalr打造即時通訊@Tech day geek
 
Real World ASP.NET MVC
Real World ASP.NET MVCReal World ASP.NET MVC
Real World ASP.NET MVC
 
非常靠谱 Html 5
非常靠谱 Html 5 非常靠谱 Html 5
非常靠谱 Html 5
 

Mehr von Jollen Chen

Flowchain blockchain classroom at Taiwan Tech University
Flowchain blockchain classroom at Taiwan Tech UniversityFlowchain blockchain classroom at Taiwan Tech University
Flowchain blockchain classroom at Taiwan Tech UniversityJollen Chen
 
Bitmark and Hyperledger Workshop: the Digital Assets and Property
Bitmark and Hyperledger Workshop: the Digital Assets and PropertyBitmark and Hyperledger Workshop: the Digital Assets and Property
Bitmark and Hyperledger Workshop: the Digital Assets and PropertyJollen Chen
 
Introducing the Blockchain and Distributed Ledger Technology
Introducing the Blockchain and  Distributed Ledger TechnologyIntroducing the Blockchain and  Distributed Ledger Technology
Introducing the Blockchain and Distributed Ledger TechnologyJollen Chen
 
Open IoT Cloud Architecture, Web of Things, Shenzhen, China.
Open IoT Cloud Architecture, Web of Things, Shenzhen, China.Open IoT Cloud Architecture, Web of Things, Shenzhen, China.
Open IoT Cloud Architecture, Web of Things, Shenzhen, China.Jollen Chen
 
Android Wear SDK: Level 101
Android Wear SDK: Level 101Android Wear SDK: Level 101
Android Wear SDK: Level 101Jollen Chen
 
Startup eng-camp 3
Startup eng-camp 3Startup eng-camp 3
Startup eng-camp 3Jollen Chen
 
讓 HTML5 走進 IPTV Framework
讓 HTML5 走進 IPTV Framework讓 HTML5 走進 IPTV Framework
讓 HTML5 走進 IPTV FrameworkJollen Chen
 
課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(2)
課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(2)課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(2)
課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(2)Jollen Chen
 
課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(3)
課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(3)課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(3)
課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(3)Jollen Chen
 
課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(1)
課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(1)課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(1)
課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(1)Jollen Chen
 
Android HAL Introduction: libhardware and its legacy
Android HAL Introduction: libhardware and its legacyAndroid HAL Introduction: libhardware and its legacy
Android HAL Introduction: libhardware and its legacyJollen Chen
 
Jollen's Presentation: Introducing Android low-level
Jollen's Presentation: Introducing Android low-levelJollen's Presentation: Introducing Android low-level
Jollen's Presentation: Introducing Android low-levelJollen Chen
 
Embedded Linux: Introduction
Embedded Linux: IntroductionEmbedded Linux: Introduction
Embedded Linux: IntroductionJollen Chen
 
Android Application: Introduction
Android Application: IntroductionAndroid Application: Introduction
Android Application: IntroductionJollen Chen
 
Android OS Porting: Introduction
Android OS Porting: IntroductionAndroid OS Porting: Introduction
Android OS Porting: IntroductionJollen Chen
 

Mehr von Jollen Chen (15)

Flowchain blockchain classroom at Taiwan Tech University
Flowchain blockchain classroom at Taiwan Tech UniversityFlowchain blockchain classroom at Taiwan Tech University
Flowchain blockchain classroom at Taiwan Tech University
 
Bitmark and Hyperledger Workshop: the Digital Assets and Property
Bitmark and Hyperledger Workshop: the Digital Assets and PropertyBitmark and Hyperledger Workshop: the Digital Assets and Property
Bitmark and Hyperledger Workshop: the Digital Assets and Property
 
Introducing the Blockchain and Distributed Ledger Technology
Introducing the Blockchain and  Distributed Ledger TechnologyIntroducing the Blockchain and  Distributed Ledger Technology
Introducing the Blockchain and Distributed Ledger Technology
 
Open IoT Cloud Architecture, Web of Things, Shenzhen, China.
Open IoT Cloud Architecture, Web of Things, Shenzhen, China.Open IoT Cloud Architecture, Web of Things, Shenzhen, China.
Open IoT Cloud Architecture, Web of Things, Shenzhen, China.
 
Android Wear SDK: Level 101
Android Wear SDK: Level 101Android Wear SDK: Level 101
Android Wear SDK: Level 101
 
Startup eng-camp 3
Startup eng-camp 3Startup eng-camp 3
Startup eng-camp 3
 
讓 HTML5 走進 IPTV Framework
讓 HTML5 走進 IPTV Framework讓 HTML5 走進 IPTV Framework
讓 HTML5 走進 IPTV Framework
 
課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(2)
課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(2)課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(2)
課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(2)
 
課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(3)
課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(3)課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(3)
課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(3)
 
課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(1)
課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(1)課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(1)
課程名稱:八屏一雲時代來臨 教你HTML5六小時打通(1)
 
Android HAL Introduction: libhardware and its legacy
Android HAL Introduction: libhardware and its legacyAndroid HAL Introduction: libhardware and its legacy
Android HAL Introduction: libhardware and its legacy
 
Jollen's Presentation: Introducing Android low-level
Jollen's Presentation: Introducing Android low-levelJollen's Presentation: Introducing Android low-level
Jollen's Presentation: Introducing Android low-level
 
Embedded Linux: Introduction
Embedded Linux: IntroductionEmbedded Linux: Introduction
Embedded Linux: Introduction
 
Android Application: Introduction
Android Application: IntroductionAndroid Application: Introduction
Android Application: Introduction
 
Android OS Porting: Introduction
Android OS Porting: IntroductionAndroid OS Porting: Introduction
Android OS Porting: Introduction
 

Backbone.js and MVW 101

  • 1. Mokoversity Backbone & MVW 101 2014.8.20 Jollen Chen <jollen@jollen.org> www.mokoversity.com
  • 3. Single Page Web Apps Source: http://apievangelist.com/2013/05/23/ember-angular-backbone-single-page- applications-and-apis/
  • 4. Through a RESTful API Source: http://cyberasylum.janithw.com/tag/single-paged-applications/
  • 5. MVC for Client Simple MVC framework ⾄至少要能將 Code 與 View 分開。View ⼜又包含 Presentation 與 UI。 http://blog.oscarliang.net/simple-mvc-framework-tutorial-part-2/
  • 6. SPAs and RESTful It’s difficult to build Single Page Applications that by simply using jQuery or MooTools. They don’t have formal structure. The browser is no longer the only client, we now have mobile devices, tablet devices, Google Goggles and electronic fridges etc. Single-page web apps are the future. Backbone.js is essentially MVC for the client and allows you to make your code modular. http://backbonetutorials.com/why-would-you-use-backbone/
  • 7. URL Router Source: http://msdn.microsoft.com/en-us/magazine/hh288078.aspx
  • 8. Mokoversity MVC, MVP 與 MVVM 觀念介紹
  • 9. URL Router Source: http://khatrishashank.wordpress.com/2013/10/11/a-comparison-of-architectural- patternsmvvm-and-mvc/
  • 12. MVC vs MVVM MVC MVVM 寫程式不⽤用寫程式 Template + Control Logic Template + Data Binding
  • 13. MVC vs MVP MVC MVP Controller 處理 User Inputs View 處理 User Inputs Controller uses Presentation Model Controller is Presentation Model
  • 15. MV* - Whatever 寫的好就是 MVP,寫不好就是 MVC;神⼈人級寫出來就是 MVVM。連 MVC 都沒有的是幼幼班。 Source: http://www.ace-dnn.com/knowledge-base/implementation-of-mvvm-design- pattern-in-dnn.aspx
  • 17. MVC 初體驗 • 將以⼀一個 TicTacToe 遊戲的實作: • 了解 MVC 的重點性 • MVC 的基本實作觀念
  • 18. REST 與 JSON • 將 REST API 回傳的 JSON 資料,轉換成 HTML5 標籤,並顯⽰示在 UI 上 • 使⽤用 jQuery AJAX 呼叫 REST API 是⽐比較 Dirty 的⽅方式 • 須導⼊入 MVC 的框架
  • 19. Key-Value Pairs • JSON 資料格式 • 將 JSON「套⽤用」到 Template { "name": "jollen"}
  • 20. 使⽤用 AJAX 呼叫 REST API // 等候 HTML ⽂文件完成載⼊入! $(document).ready(function(){! ! initSubmitForm();! });! ! var initSubmitForm = function() {! // 使⽤用 ajax() 來呼叫 REST API! $.ajax({! url: 'http://localhost:3000/discussion/latest/3',! type: "GET",! dataType: "json",! complete: function(data, textStatus, jqXHR) {! console.log(textStatus);! },! success: function (data, textStatus, jqXHR) {! console.log(data);! }! });! ! return false;! };
  • 21. 沒有 MVC 架構 • 典型沒有 MVC 架構的寫法 var dataMapping = function(data) {! for (i = 0; i < data.length; i++) {! var htmlCode = ! "<div class="alert alert-dismissable alert-info">"! + " <button type="button" class="close" data-dismiss=" alert" aria-hidden="true">×</button>"! + " <h4>jollen</h4>"! + data[i].message! +"</div>";! ! $('#message').append(htmlCode);! }! }
  • 22. 關於 RESTful • 現代的 Web App 開發,以 REST API 的⽅方式 整合 Client(Device)與 Server • RESTful 是 Web Service 主流架構 • RESTful 易於 Web Service 與不同裝置的整 合,例如:Desktop、Phone、Tablet 與 TV 等
  • 23. 安裝 Underscore 與 Backbone • Step 1:安裝 Underscore 與 Backbone • http://underscorejs.org/underscore-min.js • http://backbonejs.org/backbone-min.js • 存放⾄至 nodejs-chat 專案的 client/ javascripts/ ⺫⽬目錄下 • Backbone 必須與 Underscore 搭配使⽤用。
  • 24. 建⽴立主要⾴頁⾯面 • Step 2:修改 chat.html • 順序不能改變,先引⼊入 Underscore 後, 再引⼊入 Backbone • Backbone 是⼀一個 MVC 框架,其中 View 的部份由 Underscore ⽀支援 <script type='text/javascript' src="javascripts/underscore-min.js"></script>! <script type='text/javascript' src="javascripts/backbone-min.js"></script>
  • 25. 撰寫基本的 Backbone 框架 • Step 3:重新 撰寫 client/ javascripts/ app.js /**! * SETUP! **/! var app = app || {};! ! /**! * MODELS! **/! !! /**! * VIEWS! **/! app.MessageView = Backbone.View.extend({! events: {! },! });! ! /**! * BOOTUP! **/! $(document).ready(function() {! app.messageView = new app.MessageView();! });
  • 26. Backbone 初體驗 • Backbone 是⼀一個 MVC (MVW) 框架,⼀一開始先 定義 Model 與 View • Model 就是「表⽰示資料的模型」,也就是將會顯 ⽰示在畫⾯面上的資料 • View 的部份將負責處理 Template 與 Model 的 對應,必須先了解 Key-Value Paris 觀念 • View 的部份,也負責處理控制的部份,例如: Button 的 click 事件
  • 27. Backbone 的事件處理 • Step 4:Backbone.View 事件處理 • 為這個區塊加⼊入名字 ! <div class="row" id="message-save">! ! ! <div class="col-md-9">! ! ! ! <input class="form-control" type="text" name="message">! ! ! </div>! ! ! <div class="col-md-3">! ! ! ! <button class="btn btn-large btn-primary btn-message-save">送出</ button>! ! ! </div>! ! </div>
  • 28. 實作 Backbone 事件處理 • 使⽤用 events 屬性 1 app.MessageView = Backbone.View.extend({! 2 el: '#message-save',! 3 events: {! 4 'click .btn-message-save': 'save'! 5 },! 6 save: function() {! 7 alert("Saving...");! 8 }! 9 });
  • 30. Work with Front-End Developers Use MVC, MVP and MVVM Call REST API in Backbone way Customizable CSS CSS generation and minify
  • 31. Model, View and Control Views and Templating Handlebars.js and Underscore’s template http://addyosmani.com/resources/essentialjsdesignpatterns/book/#jquerypluginpatterns
  • 32. Model, View and Control Spine.js and Backbone.js
  • 33. Model, View and Control manage the data for an application e.g. Backbone "collections"
  • 34. MPV Models, Views & Presenters MVP is generally used most often in enterprise-level applications where it's necessary to reuse as much presentation logic as possible. http://addyosmani.com/resources/essentialjsdesignpatterns/book/#jquerypluginpatterns
  • 35. Model View ViewModel an architectural pattern based on MVC and MVP, ! which attempts to more clearly separate the development of user-interfaces (UI) from that of the business logic and behavior in an application. http://addyosmani.com/resources/essentialjsdesignpatterns/book/#jquerypluginpatterns
  • 37. 認識 View.$el • A cached jQuery object for the view's element. • ⼀一個 jQuery 物件 var message = $('input[name="message"]').val(); var message = this.$el.find('input[name="message"]').val();!
  • 38. 認識 this 物件 • this 是⼀一個物件,代表「這個 View」的意思 • this 為 Backbone.View 類別
  • 39. this.$el 與 $ • 使⽤用 *this.$el* ⽽而不是直接使⽤用 *$* 物件 • 為了避免不必要的 DOM 操作 • 將把 *$.ajax* 的做法,以 Model 的⽅方式取 代
  • 40. 認識 Backbone.Model • Backbone.Model ⽤用來表⽰示(存放)資料 • ⼀一個「資料模型」的類別
  • 41. 使⽤用 Backbone.Model • 修改 client/javascripts/app.js 1 app.Message = Backbone.Model.extend({ ! 2 defaults: {! 3 success: false,! 4 errors: [],! 5 errfor: {},! 6! 7 message: 'No message yet.'! 8 }! 9 });
  • 42. 使⽤用 Underscore • Frontend Template 系統 • 宣告 Template: <script type='text/template' id='tmpl-message'>! ! <div class="alert alert-dismissable alert-info">! ! ! <button type="button" class="close" data-dismiss="alert" aria-hidden=" true">! ! ! ! ×</button>! ! ! <h4>jollen</h4>! ! ! <%= message %>! ! </div>! </script>
  • 43. 使⽤用 Underscore 注意事項 • "type" 必須定義為 "text/template" • 給予⼀一個名字,上述範例將 Template 命名 為 "tmpl-message" • 使⽤用 <%= *variable-name* => 來取⽤用變 數值,變數名稱在上述的 Model 裡定義, Underscore 會將 Model 的變數與 Template 做對應,並且⽤用變數值取代
  • 44. Underscore 觀念⼩小結 • ViewModel:這個對應關係就是 ViewModel 的觀念 • Key-Value Pairs:Model 裡的資料,要⽤用 Key-Value Pairs 的格式表⽰示,JSON 就是 Key-Value Pairs 的格式 • Template:將 Model 裡的資料,顯⽰示到畫⾯面上,是透 過 Template,並且是由 Underscore 來完成 • Code Ignorance:如上,顯⽰示資料到畫⾯面上,不需要寫 程式;對設計師來說,只要修改 Template 即可,不會 有程式碼的困擾
  • 45. View 與 Controller • View 與 Controller 的 Binding • Code Ignorance-ViewModel 1 initialize: function() {! 2 this.model = new app.Message();! 3 this.template = _.template($('#tmpl-message').html());! 4! 5 this.model.bind('change', this.render, this);! 6 this.render();! 7 }
  • 46. View Binding 說明 • 實例化 View 時,constructor 與 initialize 會被叫 • 實作 initialize 函數來加⼊入 Model • 將 Model 的實例化存放到 View.model 裡
  • 47. Backbone 與 Underscore • 在 Backbone.View 裡定義⼀一個 template 函數 • 採⽤用的 Template 系統是 Underscore • 為 Backbone.View 定義想要使⽤用的 Template 系統 • 如何讓 Backbone.View 使⽤用 Underscore 做 為 Template 系統呢? • 將 Backbone.View.template 定義為 _.template() 即 可
  • 48. 使⽤用 Underscore • _ 是 Underscore 的物件 • Underscore 名稱的由來 • 將取得的 Template 傳給 *_.template* 即可 this.template = _.template($('#tmpl-message').html());
  • 49. 實作 render() 函數 • 在 View 裡實作 render() 函數 • render() 會將 Model 與 Template 做對應,對應後的結果就是⼀一份 HTML5 ⽂文件 render: function() {! var data = this.template(this.model.attributes);! ! this.$el.find('#message').html(data);! return this;! },
  • 50. render() 實作說明 • 先呼叫 this.template 函數,這個函數已經被定義為 Underscore Template 系統 • this.model.attributes 存放的是「Model State」 • Model State 就是 Model ⺫⽬目前所存放的資料;資料會以 JSON 的格式表 ⽰示。 • this.model.attributes 存放了 Model Data,並且是 JSON 格式 • 將 Data 交給 Template 系統去做 Data Mapping。這⾏行程式 碼是 ViewModel 觀念的靈魂。 • 最後將 Template 系統處理好的 HTML5 ⽂文件,放到想顯⽰示的 網⾴頁位置即可
  • 52. 呼叫 REST API:AJAX ⽅方式 app.MessageView = Backbone.View.extend({! el: '#message-save',! events: {! 'click .btn-message-save': 'save'! },! save: function() {! var message = $('input[name="message"]').val();! ! $.ajax({! url: '/discussion/' + message,! type: 'POST',! dataType: "json",! success: function (data, textStatus, jqXHR) {! alert("已儲存成功");! },! complete: function (data, textStatus, jqXHR) {! }! });! }! });
  • 53. 關於 Backbone Data Model • Backbone.Model 除了表⽰示資料外,還提供 各種處理模型 • 最重要的處理模型:manage changee • ⼀一但 Model 裡的資料有變動(例如:新增、 刪除等),就要重新做 "Data Mapping" • Backbone Way 的處理⽅方式,是透過 Backbone.Model.fetch
  • 54. 使⽤用 Backbone Data Model 的理由 • 使⽤用 *$.ajax() 來呼叫 REST API 雖然是可⾏行 的做法,但是有⼀一個缺點:處理 Response data 的架構不夠嚴謹 • 使⽤用 *$.ajax() 來呼叫 REST API 時,是直接 把 API 當做 *ajax() 的參數,這個做法有⼀一 個缺點:API 與 Response data 是⼀一種⽐比較 鬆散的關係
  • 55. Backbone Data Model 優點 • 使⽤用 Model fetch 的⽅方式,讓 Response data 的處理更嚴謹 • 使⽤用 Data model 的⽅方式,,讓 Data 與 API 偶和(Aggregation)在⼀一起
  • 56. 使⽤用 Backbone.Model.fetch this.model.fetch({! success: function(model, response, options) {! }! });
  • 57. 修改 Model • Backbone.Model.fetch 根據 this.model 裡的 url 定義,來呼叫 REST API app.Message = Backbone.Model.extend({! url: '/discussion/latest/5',! defaults: {! success: false,! errors: [],! errfor: {},! ! message: 'No message yet.',! messages: []! }! });
  • 58. 設定 Data Model • 呼叫 Backbone.Model.fetch 後, Backbone 會幫我們呼叫 REST API,並且取 得 Response data • 成功取得 Response data, Backbone.Model.fetch 就會 Callback success 函數。
  • 59. 關於 Data State 的變化 • self.model.set 的意思是,將取得的 response data 儲存到 Data model裡 • 由於 Data model 有了變動,所以 Backbone 便會呼叫 render() 函數 • 在 render() 函數裡,再 Render 出新的內容
  • 60. 觀念⼩小結 • 透過 Data model 整合 REST API,以及 Response data • 將 REST API 與 Response data 封裝成 Data model • 在 Data model 變動時,重新 Render 畫⾯面
  • 61. 使⽤用 Backbone.Collection app.PostCollection = Backbone.Collection.extend({! ! model: app.Post! });!