mirror of
https://github.com/jashkenas/backbone.git
synced 2026-04-08 03:00:26 -04:00
Merging in Collection#toJSON
This commit is contained in:
@@ -329,10 +329,11 @@
|
||||
// The default model for a collection is just a **Backbone.Model**.
|
||||
// This should be overridden in most cases.
|
||||
model : Backbone.Model,
|
||||
|
||||
// Return a array containing each model's toJSON result.
|
||||
|
||||
// The JSON representation of a Collection is an array of the
|
||||
// models' attributes.
|
||||
toJSON : function() {
|
||||
return this.models.map(function(model){ return model.toJSON(); })
|
||||
return this.map(function(model){ return model.toJSON(); });
|
||||
},
|
||||
|
||||
// Add a model, or list of models to the set. Pass **silent** to avoid
|
||||
|
||||
21
index.html
21
index.html
@@ -180,6 +180,7 @@
|
||||
<li>– <a href="#Collection-model">model</a></li>
|
||||
<li>– <a href="#Collection-constructor">constructor / initialize</a></li>
|
||||
<li>– <a href="#Collection-models">models</a></li>
|
||||
<li>– <a href="#Collection-toJSON">toJSON</a></li>
|
||||
<li>– <a href="#Collection-Underscore-Methods"><b>Underscore Methods (25)</b></a></li>
|
||||
<li>– <a href="#Collection-add">add</a></li>
|
||||
<li>– <a href="#Collection-remove">remove</a></li>
|
||||
@@ -849,6 +850,26 @@ var tabs = new TabSet([tab1, tab2, tab3]);
|
||||
to access model objects, but occasionally a direct reference to the array
|
||||
is desired.
|
||||
</p>
|
||||
|
||||
<p id="Collection-toJSON">
|
||||
<b class="header">toJSON</b><code>collection.toJSON()</code>
|
||||
<br />
|
||||
Return an array containing the attributes hash of each model in the
|
||||
collection. This can be used to serialize and persist the
|
||||
collection as a whole. The name of this method is a bit confusing, because
|
||||
it conforms to
|
||||
<a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript's JSON API</a>.
|
||||
</p>
|
||||
|
||||
<pre class="runnable">
|
||||
var collection = new Backbone.Collection([
|
||||
{name: "Tim", age: 5},
|
||||
{name: "Ida", age: 26},
|
||||
{name: "Rob", age: 55}
|
||||
]);
|
||||
|
||||
alert(JSON.stringify(collection));
|
||||
</pre>
|
||||
|
||||
<p id="Collection-Underscore-Methods">
|
||||
<b class="header">Underscore Methods (25)</b>
|
||||
|
||||
@@ -82,6 +82,10 @@ $(document).ready(function() {
|
||||
equals(coll.one, 1);
|
||||
});
|
||||
|
||||
test("Collection: toJSON", function() {
|
||||
equals(JSON.stringify(col), '[{"id":1,"label":"d"},{"id":2,"label":"c"},{"id":3,"label":"b"},{"id":4,"label":"a"}]');
|
||||
});
|
||||
|
||||
test("Collection: Underscore methods", function() {
|
||||
equals(col.map(function(model){ return model.get('label'); }).join(' '), 'd c b a');
|
||||
equals(col.any(function(model){ return model.id === 100; }), false);
|
||||
|
||||
Reference in New Issue
Block a user