View
Backbone 的 Views 用来接收用户的操作和修改 Model 的数据 ,另外通过 render 来展示数据.
实际上,在MVC框架中,它更像是Controller。
View有两个作用:
1.监听事件
2.展示数据
下面简单的创建一个View:
- GameView= Backbone.View.extend({
- tagName : "div",
- className: "game",
- render : function() {
- // code for rendering the HTML for the view
- }
- });
下面让我们看看render部分应该怎么写。如下:
- render : function() {
- this.el.innerHTML = this.model.get('name');
- //Or the jQuery way
- $(this.el).html(this.model.get('name'));
- }
更全面的示例:
var DocumentView = Backbone.View.extend({
events: {
"dblclick" : "open",
"click .icon.doc" : "select",
"contextmenu .icon.doc" : "showMenu",
"click .show_notes" : "toggleNotes",
"click .title .lock" : "editAccessLevel",
"mouseover .title .date" : "showTooltip"
},
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
return this;
},
open: function() {
window.open(this.model.get("viewer_url"));
},
select: function() {
this.model.set({selected: true});
},
...
});
events部分是监听的事件,下面的open、select方法是事件对应的处理。
Controller(新版为Router)
controller 将不同的以#开头的 URL 片段 绑定到不同的函数,实现服务器端 MVC 模型中的 router 一样的功能.
- var Hashbangs = Backbone.Controller.extend({
- routes: {
- "!/": "root",
- "!/games": "games",
- },
- root: function() {
- // Prep the home page and render stuff
- },
- games: function() {
- // Re-render views to show a collection of books
- },
- });
!/games 就会映射到games函数,浏览器地址栏中会变成 domain/#!/games
值得提出的是 Backbone 的 router 也支持正则表达式的匹配
var Workspace = Backbone.Controller.extend({
routes: {
"help": "help", // #help
"search/:query": "search", // #search/kiwis
"search/:query/p:page": "search" // #search/kiwis/p7
},
help: function() {
...
},
search: function(query, page) {
...
}
});