Backbone学习笔记 - Collection及Router篇

时间:2023-07-16 23:11:44

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