backbone.js and mvw 101

Post on 09-Jul-2015

329 Views

Category:

Engineering

2 Downloads

Preview:

Click to see full reader

DESCRIPTION

Introducing MVW and Backbone.js at 101 level.

TRANSCRIPT

Backbone & MVW 101 2014.8.20

Jollen Chen <jollen@jollen.org>

www.mokoversity.com

Mokoversity

為什麼需要 Backbone.js ?

Mokoversity

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

http://blog.oscarliang.net/simple-mvc-framework-tutorial-part-2/

Simple MVC framework ⾄至少要能將 Code 與 View 分開。View ⼜又包含 Presentation 與 UI。

SPAs and RESTful

http://backbonetutorials.com/why-would-you-use-backbone/

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.

URL Router

Source: http://msdn.microsoft.com/en-us/magazine/hh288078.aspx

MVC, MVP 與 MVVM 觀念介紹

Mokoversity

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

Source: http://www.ace-dnn.com/knowledge-base/implementation-of-mvvm-design-pattern-in-dnn.aspx

寫的好就是 MVP,寫不好就是 MVC;神⼈人級寫出來就是 MVVM。連 MVC 都沒有的是幼幼班。

TicTacToe

Mokoversity

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 });

MV Whatever

Mokoversity

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 ViewModelan 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

View and Model

Mokoversity

認識 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 ⽂文件,放到想顯⽰示的網⾴頁位置即可

Invoke RESTful API

Mokoversity

呼叫 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!});!

top related