Collections and mixins
Fetch a list repos and render them
The repos will be stored in a collection. Creates two files in dir models. repo.js and repocollection.js
// **** repo.js ****
import Model from 'ampersand-model'
export default Model.extend({
props: {
id: 'number',
name: 'string',
full_name: 'string'
}
})
Checks the API on developer.github.com/v3/repos to see what we get back.He's using id, name, full_name (see above)
Then creates the repocollection. Collection is an observable array of "stuff".
// **** repo-collection.js ****
import Colleciton from 'ampersand-rest-collection'
// (slighlty different from Backbone )
// extends a normal collection
import Repo from './repo'
export default Collection.extend({
url: 'https://api.github.com/user/repos', // (from the github api docs)
model: Repo, // see explanation below
})
Above is a restful collection, an extension of the normal collection. Rest collection extends collection with some networking related methods.
Notice above:
We want to fetch, but we also have to give the authorisation header. We already did this in the me model (me.js). We're going to pull it out for a general method.model: Repo
-> It turns any plain object into a model (if not already one)Creates models/helpers
A folder for generic components. If they are generic enough you can put on npm.
In models/helpers creates github-mixins.js
// ++++ 0. create the file
// **** models/helpers/github-mixins.js ****
import app from 'ampersand-app'
export default {
//++++ 1. cut and paste from me.js
ajaxConfig () {
return {
headers: {
// ++++ 2. token will be on app
Authorization: 'token' + app.me.token
}
}
}
}
Add this mixin to repo-collection.js
// **** repo-collection.js ****
import Colleciton from 'ampersand-rest-collection'
import Repo from './repo'
// ++++ 1. add the mixin
import githubMixin from '../helpers/github-mixin'
// ++++ 2. add githubMixin as a parameter
// if you add it here it's clear where it's coming from
export default Collection.extend(githubMixin, {
url: 'https://api.github.com/user/repos',
model: Repo,
})
Do the same for me.js (not shown here...)