Backbone Collection 学习笔记

Backbone.Collection   集合

集合是模型的有序组合,我们可以在集合上绑定change 事件,也可以监听add和remove事件,   从服务器更新,并使用Unserscore.js 提供的方法

集合中的模型触发的任何事件都可以在集合身上触发,可以监听集合中模型的变化

Documents.bind("change:selected",)        


extend Backbone.Collection.extend(properties,[classProperties])

生成一个collection类。实例属性参数properties以及类属性参数classProperties  会被直接注册到集合的构造函数


model collection.model  

指定集合的模型类。可以传入 原始属性对象(和数组)   add .create   以及reset ,传入的属性会被自动转换为适合的模型类型

var Library = Backbone.Collection.extend({

  model:Book

});


constructor/initialize   new Collection([models],[option])

创建集合时,可以传入初始的模型数组。集合的comparator 函数也可以做为选项传入。如果定义了initialize函数,会在集合创建时调用 

var tabs = new TabSet([tab1,tab2,tab3]);


models   collection.models

集合中模型的原始值,通常我们使用get ,at     也可直接访问


toJSON  collection.toJSON()

返回集合中包含的每个模型对象的数组。

var collection = new Backbone.Collection(

[

{name:"Tim",age:5},

{name:"Ysw",age:2},

]

);

 

alert(JSON.stringify(collection));


Underscore  方法

Backbone 代理了Underscore.js ,   提供了26个迭代函数.

Books.each(function(book){

  book.publish();

});


var titles = Books.filter(function(book){

  return book.get("published") === true;

})

var alphabetical = Books.sortBy(function(book) {
  return book.author.get("name").toLowerCase();
});

add方法    collection.add(models,[option])
向集合中增加模型,会触发add事件,可以传入{silent:true}关闭。如果定义了模型属性,也可以传入 原始的属性对象让其看顾起来像一个模型实例。  传入{at:index}设置插入位置
var ships = new Backbone.Collection;
ships.bind("add",function(ship){
  alert("Ahoy " + ship.get("name")  + "!");
});
ships.add([
  {name: "Flying Qutchman"},
  {name: "Black Pearl"}
]);

remove  collection.remove(models,[option])

从模型中删除模型(或模型数组)。触发remove事件

get collection.get(id)

从集合中返回id为  id的模型

at  collection.at(index)

返回集合中指定索引的模型对象。


getByCid   collection.getByCid(id)


posted @ 2011-12-20 19:06  顺武  阅读(1748)  评论(0编辑  收藏  举报