Backbone学习笔记---View, Collections

在Backbone中,views并不含有markup,它们通常会用JS templating(例如:Mustache, jQuery-tmpl).一个view的render()方法可以绑定到model's change事件上,这样就可以达到不用刷新整个page,只用刷新部分就可以了。

创新一个新的View

View Code
var PhotoSearch=Backbone.View.extend({
    el:$('#results'),
    render:function(event){
      var compiled_template=_.template($('#results-template').html());
      this.$el.html(compiled_template(this.model.toJSON()));
      return this;
    },
  events:{
    "submit #searchForm":"search",
    "click .reset":"reset",
    "click .advanced":"switchContext"
  },
  search:function(event){
   //当form'#searchForm'提交的时候执行
  },
  reset:function(event){
    //当click".reset"的时候执行
  },
  switchContext:function(event){
    //当click ".advanced"的时候执行
  }
  
});

在程序中el是一个DOM element的引用,所有的views都需要有一个这样的el.它可以让所有的DOM一次性插入,它会令更快的显示而browser最小的reflow和repaint.

el可以是存在的元素,也可以是新建元素

 el: '#footer', el:document.getElementById('footer');

如果是新建元素我们可以用tagName, className, id的组合来新建一个tagName是必须的,其它两项是可选的。

events attribute

 允许我们绑定事件到自定义的selector上{"eventName selector": "callBackFunction"},有许多的event-types是被支持的包括:click, submit, mouseover, dbclick当然还有更多。

Collections:

collection是一系列models的集合,可以通过扩展Backbone.Collection来创建.请看下面的example:

View Code
var PhotoCollection=Backbone.Collection.extend({
    model: Photo
});

如何获取和设置model

var skiingEpicness=PhotoCollection.get(2);

另外,我们还可以通过它的client id来获得一个model.这个client id是Backbone自动给models产生的。你可以通过.cid属性来获得。

var mySkiingCrash=PhotoCollection.getByCid(456);

从服务器上获得model

collections.fetch()方法可以从服务器端获得一组models以JSON array的形式。

View Code
var PhotoCollection=new Backbone.Collection;
PhotoCollection.url='/photos';
PhotoCollection.fetch();

Backbone.sync每次Backbone试图读取或者存储server上的models的时候,它会用jQuery或者Zepto's ajax来执行RESTful请求。当然可以override它。

Backbone.sync=function(method, model){
   console.log("I've been passed "+method+"with "+JSON.stringfy(model));
}

 

 

 

posted @ 2012-09-08 09:23  moonreplace  阅读(646)  评论(0编辑  收藏  举报