Backbone学习笔记 - Collection及Router篇
2015-12-09 16:31
330 查看
Collection
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]
Router
Backbone.Router担任了一部分Controller的工作,他能将特定的URL或锚点与一个特定的方法绑定。
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,请依次访问下面的地址,并注意控制台的输出结果:
- http://localhost/index.html // 输出:应用入口方法
- http://localhost/index.html#topic // 输出:渲染列表方法
- http://localhost/index.html#topic/1023 // 输出:渲染详情方法, id为:1023
- http://localhost/index.html#about // 输出:URL错误, 错误信息: about
然后再使用浏览器的“前进”、“返回”等按钮进行切换,你会看到当你的URL切换时,控制台输出了对应的结果,说明它已经调用了相应的方法。而在进行这些操时,页面并没有刷新。这个例子很好地解决了我们在一开始所说的两个问题。
参考:
http://yujianshenbing.iteye.com/blog/1749831
相关文章推荐
- 图的深搜与广搜
- AndroidStudio插件GsonFormat快速实现Java实体对象
- 【转】Could not write file XXX\.classpath解决
- 【转】微信缓存、浏览器缓存等各种顽固缓存的解决方法,缓存解决方法
- 根据wsdl生成一个webservice 的.cs文件
- 关于面向对象“多态”的理解
- Jenkins + Maven + TestNG参数化调用测试用例
- squee_spoon and his Cube VI---郑大校赛(求最长子串)
- 让文字在div中居中的方法[转]
- Menu简单的菜单选项
- NSNumber的使用
- Mac下android studio 安装Genymotion插件找不到地址错误
- Application 的坑
- Spring整合Hibernate管理事务(xml配置方式)
- Volley的初级使用(从网络下载图片)
- 微信中长按弹出菜单(1) 没有实现功能
- Bug3 ---error C2039: “SetWindowTextA”: 不是“ATL::CStringT<BaseType,StringTraits>”的成员
- [ahk]浏览删除IE的用户输入的url列表
- 牛客网读书笔记
- 用httpPost对JSON发送和接收的例子