Backbone入门(View Controller)

               

View

Backbone 的 Views 用来接收用户的操作和修改 Model 的数据 ,另外通过 render 来展示数据.
实际上,在MVC框架中,它更像是Controller。

View有两个作用:
1.监听事件
2.展示数据

下面简单的创建一个View:
  1. GameView= Backbone.View.extend({  
  2.   tagName : "div",  
  3.   className: "game",  
  4.   render : function() {  
  5.     // code for rendering the HTML for the view  
  6.   }  
  7. });  

下面让我们看看render部分应该怎么写。如下:
  1. render : function() {  
  2.   this.el.innerHTML = this.model.get('name');  
  3.   
  4. //Or the jQuery way  
  5. $(this.el).html(this.model.get('name'));  
  6. }  

更全面的示例:
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 一样的功能.

简单使用:
  1. var Hashbangs = Backbone.Controller.extend({  
  2.   routes: {  
  3.     "!/":                 "root",  
  4.     "!/games":        "games",  
  5.   },  
  6.   root: function() {  
  7.     // Prep the home page and render stuff  
  8.   },  
  9.   
  10.   games: function() {  
  11.     // Re-render views to show a collection of books  
  12.   },  
  13.   });  

 !/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) {    ...  } });




           

猜你喜欢

转载自blog.csdn.net/qq_44912644/article/details/89496223
今日推荐