Collectionhtml
Collection能夠當作是Model的集合。如下是一個集合的例子:瀏覽器
var Song = Backbone.Model.extend({ defaults: { name: "Not specified", artist: "Not specified" }, initialize: function(){ console.log("Music is the answer"); } }); var Album = Backbone.Collection.extend({ model: Song }); var song1 = new Song({ name: "How Bizarre", artist: "OMC" }); var song2 = new Song({ name: "Sexual Healing", artist: "Marvin Gaye" }); var song3 = new Song({ name: "Talk It Over In Bed", artist: "OMC" }); var myAlbum = new Album([ song1, song2, song3]); console.log( myAlbum.models ); // [song1, song2, song3]
Routerspa
Backbone.Router擔任了一部分Controller的工做,他能將特定的URL或錨點與一個特定的方法綁定。code
var AppRouter = Backbone.Router.extend({ routes : { '' : 'main', 'topic' : 'renderList', 'topic/:id' : 'renderDetail', '*error' : 'renderError' }, main : function() { console.log('應用入口方法'); }, renderList : function() { console.log('渲染列表方法'); }, renderDetail : function(id) { console.log('渲染詳情方法, id爲: ' + id); }, renderError : function(error) { console.log('URL錯誤, 錯誤信息: ' + error); } }); var router = new AppRouter(); Backbone.history.start();
將例子中的代碼複製到你的頁面中。假設你的頁面地址爲http://localhost/index.html,請依次訪問下面的地址,並注意控制檯的輸出結果: router
而後再使用瀏覽器的「前進」、「返回」等按鈕進行切換,你會看到當你的URL切換時,控制檯輸出了對應的結果,說明它已經調用了相應的方法。而在進行這些操時,頁面並無刷新。這個例子很好地解決了咱們在一開始所說的兩個問題。htm
參考:blog
http://yujianshenbing.iteye.com/blog/1749831ci