Backbone.js开发第一步(三)
Backbone中的集合简单来说就是一列有序的模型。它可以被使用在例如下面例子这样的情形:
var Song .Model.({ initialize: function(){ console.("Music is the answer"); }});var Album .Collection.({ model: Song});
现在我们使用一些有用的数据来创建一个集合。
var Song .Model.({ defaults:{ name: "Not specified", artist: "Not specified" }, initialize: function(){ console.("Music is the answer"); }});var Album .Collection.({ model: Song});var song1 new ({name: "How Bizarre", artist: "OMC"}); var song2 new ({name: "Sexual Healing", artist:"Marvin Gaye"}); var song3 new ({name: "Talk It Over In Bed", artist: "OMC"});var myAlbum new ([song1,song2,song3]);console.(myAlbum.models); // [song1,song2,song3]
当使用了哈希标签(#)的时候,Backbone中的路由器用于将你的应用路由到相应的URL.在传统的MVC印象中路由似乎并不是必须的。然而Backbone中的路由器在你的应用需要URL路由/历史的功能时非常有用。
定义一个路由器需要至少一个路由以及一个映射到具体路由的函数。在下面的例子中我们将会来定义一个路由。
还要注意的一点是路由解释URL中位于”#”标签之后的任何东西。你的应用中的所有连接需要标的到”#/action”或者”#action”。(在哈希标签后面添加一个正斜杠看起来更好看,例如:?http://example.com/#/user/help)。
var AppRouter .Router.({ routes: { "*actions": "defaultRoute" //匹配 http://example.com/#anything-here } }); //初始化路由器 var app_router new ; app_router.('route:defaultRoute',function(actions){ (actions); }); //开始Backbone的历史是一个必要的步骤 Backbone.history.();var AppRouter .Router.({ routes: { "posts/:id" "getPost", "*actions": "defaultRoute" //Backbone首先会尝试匹配上面的路由 } }); //初始化路由器 var app_router new ; app_router.("route:getPost",function(id){ //注意到路由定义中的变量被传递到了这里 ("Get post number " ); }); app_router.("route:defaultRoute",function(actions){ (actions); }); //开启Backbone的history是一个必要的步骤 Backbone.history.();route:{ "posts/:id" : "getPost", //<a href="http://example.com/#/posts/121">Example</a> "download/*path": "downloadFile", //<a href="http://example.com/#/download/user/images/hey.gif">Download</a> ":route/:action": "loadView", //<a href="http://example.com/#/dashboard/graph">Load Route</a>},app_router.("route:getPost",function(id){ (id); //121});app_router.("route:downloadFile",function(path){ (path); // user/images/hey.gif});app_router.("route:loadView",function(route,action){ (route "_" ); //dashboard_graph});
路由的作用很大,在实际开发中你的应用应当包含很多路由。如果你需要实现SEO,在Google中搜索”google seo hashbangs”。你也可以查看Seo Server。