Merging in Collection#toJSON

This commit is contained in:
Jeremy Ashkenas
2010-10-20 16:01:56 -04:00
parent c957ec0888
commit f3a8dcd16b
3 changed files with 29 additions and 3 deletions

View File

@@ -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

View File

@@ -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>

View File

@@ -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);