Backbone系列之四
這個系列介紹了一個例子,有兩個view元件,一個是Droplist,一個是Table。
基本的資料格式如下所示,其中Droplist列出name,選中指定name後,在Table列出conditions陣列的內容。
{ "_id" : ObjectId("5ca3f9abd40869ed2f6bb26b"), "conditions" : [ "111", "222" ], "name" : "aaa" } { "_id" : ObjectId("5ca3f9abd40869ed2f6bb26c"), "conditions" : [ "333", "444" ], "name" : "bbb" }
之前幾天對Droplist元件、Table元件,以及兩個元件間的通訊進行了說明,今天是這個系列的最後一篇,重點介紹一下總體架構。
首先這個例子包括了一個HTML模版檔案和三個JS檔案,它們分別是
- template.html,包括基本的元件及id,完全不含js程式碼
- ctrl.js,主控程式碼,引入並建立元件
- trainsets.js,Droplist元件程式碼
- taglist.js,Table元件程式碼
先看HTML模版檔案
<div data-type="awf-container"> <select id='trainsets' data-type='awf-droplist' data-title="測試集" data-title-width="col-lg-1" data-width="col-lg-3" > </select> <button class="addTrainset" data-type="awf-button">新增集合</button> <button class="removeTrainset" data-type="awf-button">刪除集合</button> </div> <table id="taglist" data-type="awf-table"data-title='Cases' data-extBtn="addNew"> <thead> <tr> <th>分類標籤</th> <th>案例數量</th> <th>操作</th> </tr> </thead> <tbody></tbody> </table>
在這裡定義了頁面中出現的幾個主要元件:Droplist、兩個按鈕和一個Table。
主控程式碼ctrl.js
define(['text!./tpl.html', './trainsets', './taglist'], function (tpl, Trainsets, Taglist) { var controller = function () { $navView.trigger("routeChange", "n303"); $appView.html(tpl).trigger("htmlChanged"); var trainsets = new Trainsets(); var taglist = new Taglist(); trainsets.load(); controller.onRouteChange = function () { trainsets.undelegateEvents(); taglist.undelegateEvents(); }; }; return controller; });
引入了另外三個檔案,並建立了Trainsets元件和Taglist元件,呼叫load函式進行初始化。
這樣整個頁面的模組化劃分就比較清晰了,在這裡模組化的作用並不一定是要進行復用,而是便於維護,通過把不同功能劃分成不同模組,模組之間使用鬆耦合的訊息佇列方式進行通訊,實現了故障隔離和程式碼的精簡,更便於查詢錯誤和增加新功能。