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