Last active
August 29, 2015 14:13
-
-
Save pmn4/ccb5bef02743052e14e7 to your computer and use it in GitHub Desktop.
TIL: Backbone.Collection#parse
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| let's say you are trying to inflate a Backbone Collection | |
| using some endpoint which returns data in non-array form. | |
| maybe, | |
| */ | |
| { | |
| meta: { | |
| total: 25, | |
| pageSize: 3, | |
| pageNumber: 1 | |
| }, | |
| items: [ | |
| { name: "abc" }, | |
| { name: "def" }, | |
| { name: "ghi" } | |
| ] | |
| } | |
| /* | |
| You don't care about the `meta` data, you just want the `items`. | |
| So you create your collection | |
| */ | |
| RTR.Collections.Items = Backbone.Collection.extend({ | |
| url: "/items/with/meta", | |
| model: RTR.Collections.Item | |
| }); | |
| /* | |
| After visiting the Backbone Annotated source, you find that, ugh, | |
| it looks like you are going to have to override the | |
| [#fetch](http://backbonejs.org/docs/backbone.html#section-112) | |
| method just so you can tweak the success callback | |
| but what if there were a better way????????????????? | |
| Of course there is: | |
| [#parse](http://backbonejs.org/docs/backbone.html#section-114)! | |
| Your Collection can now look like this: | |
| */ | |
| RTR.Collections.Items = Backbone.Collection.extend({ | |
| url: "/items/with/meta", | |
| model: RTR.Collections.Item, | |
| parse: function (resp) { | |
| return resp.items; | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment