標籤:style blog http color 使用 io 2014 art
[來自: Backbone.js 開發秘笈 第1章]
各種模型實際上是通過擴充其基類 Backbone.Model 實現的。同理,定義的集合是靠擴充其基類 Backbone.Collection 而實現的。
控制器的功能被分散實現在 Backbone.Router 和 Backbone.View 當中。
路由器負責處理 URL 的變化,並且委派一個視圖來繼續處理應用。路由器(非同步)擷取模型後,隨即觸發一個視圖的更新操作。
視圖負責監聽 DOM 事件。它要麼對模型進行更新,要麼通過路由器轉移到應用的其他部分。
Backbone 依賴 Underscore , JQuery 或 Zepto 。
Backbone.Router 只是用來定義路由以及相關的回呼函數,而其他所有的重要工作則全部都由 Backbone.history 完成。作為視窗中的全域路由器, Backbone.history 負責處理 hashchange 或者 pushState 事件、匹配到合適的路由以及觸發回呼函數。你永遠不用為( Backbone.history )這個全域路由器建立一個執行個體,因為到你使用路由器時, Backbone 會自動建立。
Backbonejs 外掛程式: https://github.com/jashkenas/backbone/wiki/Extensions,-Plugins,-Resources
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8"/> <title></title> <script src="lib/jquery.js"></script> <script src="lib/underscore.js"></script> <script src="lib/backbone.js"></script> <script src="js/main.js"></script> </head><body></body></html>index.html
(function ($) { $(function () { /* define */ //Mode-------------------------------------------------- var InvoiceItemMode = Backbone.Model.extend({ defaults: { price: 0, quantity: 0 }, calculateAmount: function () { return this.get(‘price‘) * this.get(‘quantity‘); } }); //View--------------------------------------------------- var PreviewInvoiceItemView = Backbone.View.extend({ template: _.template(‘Price: <%= price %>. Quantity: <%= quantity %>. Amount: <%= amount %>.‘), render: function () { var html = this.template({ price: this.model.get(‘price‘), quantity: this.model.get(‘quantity‘), amount: this.model.calculateAmount() }); $(this.el).html(html); } }); //Router------------------------------------------------- var Workspace = Backbone.Router.extend({ routes: { ‘‘: ‘invoiceList‘, ‘invoice‘: ‘invoiceList‘ }, invoiceList: function () { var invoiceListView = new PreviewInvoiceItemView({ model: new InvoiceItemMode({ price: 2, quantity: 3 }), el: ‘body‘ }); invoiceListView.render(); } }); /* apply */ //instance----------------------------------------------- /* var invoiceItemMode = new InvoiceItemMode({ price: 2, quantity: 3 }); var previewInvoiceItemView = new PreviewInvoiceItemView({ model: invoiceItemMode, el: ‘body‘ }); */ //execute------------------------------------------------ //previewInvoiceItemView.render(); new Workspace(); Backbone.history.start(); });})(jQuery);main.js