Backbone proxies to
Underscore.js
to provide 28 iteration functions on
Backbone.Collection
. They aren't all documented here, but you can take a look at the Underscore documentation for the full details…
这里有许多的可以用来循环backbone.collection的方法,具体可以在官方网站查看:
books.each(function(book) { book.publish(); }); var titles = books.map(function(book) { return book.get("title"); }); var publishedBooks = 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, [options])
Add a model (or an array of models) to the collection, firing an "add"
event. If a model
property is defined, you may also pass raw attributes objects, and have them be vivified as instances of the model. Pass {at: index}
to splice the model into the collection at the specified index
. If you're adding models to the collection that are
already
in the collection, they'll be ignored, unless you pass {merge: true}
, in which case their attributes will be merged into the corresponding models, firing any appropriate "change"
events.
var ships = new Backbone.Collection; ships.on("add", function(ship) { alert("Ahoy " + ship.get("name") + "!"); }); ships.add([ {name: "Flying Dutchman"}, {name: "Black Pearl"} ]);
remove
collection.remove(models, [options])
Remove a model (or an array of models) from the collection. Fires a "remove" event, which you can use silent
to suppress. The model's index before removal is available to listeners as options.index
.
Example:
var ships = new Backbone.Collection;
ships.on('add',function(ship){
//alert(ships.index);
//alert('Add Ship name : ' + ship.get('name'));
})
ships.on('remove',function(ship,ships,options){
alert(options.index);
})
ships.add([
{name:'Andy1'},
{name:'andy2'},
{name:'Andy1'},
]);
ships.remove(ships.findWhere({name:'andy2'}));
console.log(JSON.stringify(ships));
reset
collection.reset([models], [options])
Adding and removing models one at a time is all well and good, but sometimes you have so many models to change that you'd rather just update the collection in bulk. Use
reset to replace a collection with a new list of models (or attribute hashes), triggering a single "reset" event at the end. For convenience, within a "reset" event, the list of any previous models is available as options.previousModels.
Calling collection.reset()
without passing any models as arguments will empty the entire collection.
set
collection.set(models, [options])
The
set
method performs a "smart" update of the collection with the passed list of models. If a model in the list isn't yet in the collection it will be added; if the model is already in the collection its attributes will be merged; and if the collection contains any models that
aren't
present in the list, they'll be removed. All of the appropriate "add"
, "remove"
, and "change"
events are fired as this happens. If you'd like to customize the behavior, you can disable it with options: {add: false}
, {remove: false}
, or {merge: false}
.
var ships = new Backbone.Collection; ships.add([ {name:'Andy1'}, {name:'andy2'}, {name:'Andy1'}, ]); ships.set({name:'andy2'}); //会触发remove事件 console.log(JSON.stringify(ships)); //输出来到数据没有了Andy1的Model,默认已经通过set删除了。
get
collection.get(id)
Get a model from a collection, specified by an id
, a cid
, or by passing in a
model
.
var ships = new Backbone.Collection; ships.add([ {id:1,name:'Andy1'}, {id:2,name:'andy2'}, {id:3,name:'Andy1'}, ]); console.log(JSON.stringify(ships)); ships.remove(ships.get(2)); //remove the model which id = 2 console.log(JSON.stringify(ships));
at
collection.at(index)
Get a model from a collection, specified by index. Useful if your collection is sorted, and if your collection isn't sorted,
at
will still retrieve models in insertion order.
var ships = new Backbone.Collection; ships.add([ {id:1,name:'Andy1'}, {id:2,name:'andy2'}, {id:3,name:'Andy1'}, ]); alert(ships.at(1).get('name'));
注意:这个at的index是从0开始的。
push
collection.push(model, [options])
Add a model at the end of a collection. Takes the same options as add
.
pop
collection.pop([options])
Remove and return the last model from a collection. Takes the same options as remove
.
unshift
collection.unshift(model, [options])
Add a model at the beginning of a collection. Takes the same options as add 。
shift
collection.shift([options])
Remove and return the first model from a collection. Takes the same options as remove
.
slice
collection.slice(begin, end)
Return a shallow copy of this collection's models, using the same options as native Array#slice
.
var ships = new Backbone.Collection;
ships.add([
{id:1,name:'Andy1'},
{id:2,name:'andy2'},
{id:3,name:'Andy1'},
{id:4,name:'Andy4'},
{id:5,name:'Andy5'},
{id:6,name:'Andy6'},
]);
console.log(ships.slice(2,5)); //通过输出可以发现,slice(2,5)其实是不包含2(这个2代表是从第二个Model开始,不包括第二个),包含5的。得到的id分别是id=3,id=4,id=5。
length
collection.length
Like an array, a Collection maintains a length
property, counting the number of models it contains.
comparator
collection.comparator
(需要自己进行定义)
By default there is no
comparator
for a collection. If you define a comparator, it will be used to maintain the collection in sorted order. This means that as models are added, they are inserted at the correct index in
collection.models (当你新的添加一个Model的时候,可以通过定义这个comparator方法判定插入的index)。A comparator can be defined as a sortBy (pass a function that takes a single argument), as a sort (pass a comparator function that expects two arguments), or as a string indicating the attribute to sort by.
如果我们的comparator是作为sortBy或sort定义了的话,判定如下:
"sortBy" comparator functions take a model and return a numeric or string value by which the model should be ordered relative to others. "sort" comparator functions take two models, and return -1
if the first model should come before the second, 0
if they are of the same rank and 1
if the first model should come after.
sortBy比较函数需要一个Model参数并且返回一个数字或字符串。
sort比较函数需要2个Model作为参数,会返回-1,1和0。-1表示第一个Model在第二个Mode前面;0表示一样;1表示第一个Model应该在第二个Model后面。
var Chapter = Backbone.Model; var chapters = new Backbone.Collection; chapters.comparator = function(chapter) { return chapter.get("page"); }; chapters.add(new Chapter({page: 9, title: "The End"})); chapters.add(new Chapter({page: 5, title: "The Middle"})); chapters.add(new Chapter({page: 1, title: "The Beginning"})); alert(chapters.pluck('title'));
sort
collection.sort([options])
Force a collection to re-sort itself. You don't need to call this under normal circumstances, as a collection with a comparator
will sort itself whenever a model is added. To disable sorting when adding a model, pass {sort: false}
to add
. Calling
sort
triggers a "sort"
event on the collection.
var Chapter = Backbone.Model; var chapters = new Backbone.Collection; chapters.comparator = function(chapter) { return chapter.get("page"); }; chapters.add(new Chapter({page: 9, title: "The End"})); chapters.add(new Chapter({page: 5, title: "The Middle"})); chapters.add(new Chapter({page: 1, title: "The Beginning"}),{sort:false}); //对这次新增的Model不要排序 chapters.sort(); //调用sort函数又会进行一次排序 alert(chapters.pluck('title'));
pluck
collection.pluck(attribute)
Pluck an attribute from each model in the collection. Equivalent to calling map
and returning a single attribute from the iterator.(提取每个Model里面要求的属性)
var stooges = new Backbone.Collection([ {name: "Curly"}, {name: "Larry"}, {name: "Moe"} ]); var names = stooges.pluck("name"); alert(JSON.stringify(names));
where
collection.where(attributes)
Return an array of all the models in a collection that match the passed
attributes
. Useful for simple cases of filter
.
var friends = new Backbone.Collection([ {name: "Athos", job: "Musketeer"}, {name: "Porthos", job: "Musketeer"}, {name: "Aramis", job: "Musketeer"}, {name: "d'Artagnan", job: "Guard"}, ]); var musketeers = friends.where({job: "Musketeer"}); console.log(JSON.stringify(musketeers)); alert(musketeers.length);
findWhere
collection.findWhere(attributes)
Just like where
, but directly returns only the first model in the collection that matches the passed
attributes
.
url
collection.url or collection.url()
Set the
url
property (or function) on a collection to reference its location on the server. Models within the collection will use
url to construct URLs of their own.
var Notes = Backbone.Collection.extend({ url: '/notes' }); // Or, something more sophisticated: var Notes = Backbone.Collection.extend({ url: function() { return this.document.url() + '/notes'; } });
parse
collection.parse(response, options)
parse
is called by Backbone whenever a collection's models are returned by the server, in fetch
. The function is passed the raw response
object, and should return the array of model attributes to be added
to the collection. The default implementation is a no-op, simply passing through the JSON response. Override this if you need to work with a preexisting API, or better namespace your responses.
var Tweets = Backbone.Collection.extend({ // The Twitter Search API returns tweets under "results". parse: function(response) { return response.results; } });
clone
collection.clone()
Returns a new instance of the collection with an identical list of models.
fetch
collection.fetch([options])
Fetch the default set of models for this collection from the server, setting
them on the collection when they arrive. The
options
hash takes success
and error
callbacks which will both be passed (collection, response, options)
as arguments. When the model data returns from the server, it uses set
to (intelligently) merge the fetched models, unless you pass {reset: true}
, in which case the collection will be (efficiently) reset
. Delegates to Backbone.sync
under the covers for custom persistence strategies and returns a jqXHR
. The server handler for
fetch
requests should return a JSON array of models.
Backbone.sync = function(method, model) { alert(method + ": " + model.url); }; var accounts = new Backbone.Collection; accounts.url = '/accounts'; accounts.fetch();
he behavior of
fetch
can be customized by using the available set
options. For example, to fetch a collection, getting an "add"
event for every new model, and a "change"
event for every changed existing model, without removing anything: collection.fetch({remove: false})
jQuery.ajax
options can also be passed directly as
fetch
options, so to fetch a specific page of a paginated collection: documents.fetch({data: {page: 3}})
Note that fetch
should not be used to populate collections on page load — all models needed at load time should already be bootstrapped
in to place.
fetch
is intended for lazily-loading models for interfaces that are not needed immediately: for example, documents with collections of notes that may be toggled open and closed.
create
collection.create(attributes, [options])
Convenience to create a new instance of a model within a collection. Equivalent to instantiating a model with a hash of attributes, saving the model to the server, and adding the model to the set after being successfully created. Returns the new model 。
The
create
method can accept either an attributes hash or an existing, unsaved model object。
Creating a model will cause an immediate "add" event to be triggered on the collection, a "request" event as the new model is sent to the server, as well as a"sync" event, once the server has responded with the successful creation of the model. Pass {wait: true} if you'd like to wait for the server before adding the new model to the collection.
var Book = Backbone.Model.extend({
sync : function(method,model){
alert(method + ' ' + model.get('author'));
}
});
var Library = Backbone.Collection.extend({
model: Book
});
var nypl = new Library;
var othello = nypl.create({
title: "Othello",
author: "William Shakespeare"
});