Collections
AJAX Abstraction for Lists of Resources
AJAX Abstraction for Lists of Resources
The url
is the location of the API endpoint used for fetching the resources associated with this collection.
This property can be either a string
or a function
that returns a string.
The default implementation looks like this:
url: '',
The equivalent function version would look like this:
url: function() {
return '';
},
A common use for this method is to construct nested URLs.
Many REST API endpoints have flat URLs, like /tweets
or /users
. But some APIs require you to use a nested URL structure like /users/1/tweets
when fetching or updating data.
The code below shows how you can use initialize()
and url()
to accomplish this:
import { Collection } from 'lore-models';
const TweetCollection = Collection.extend({
initialize: function(attributes, options){
this.user = options.user;
},
url: function() {
return `http://localhost:1337/users/${this.user}/tweets`
}
})
const tweets = new TweetCollection([], {
user: 1
})
tweets.fetch()
In the code above, we're providing a second argument to new TweetCollection()
, and that additional information is passed to initialize()
as options
, where we save the id for the user
.
Then we override the url()
, and provide a method to compose the nested URL endpoint using the user
.
When we call tweets.fetch()
it will make an API call to http://localhost:1337/users/1/tweets
, and you can confirm the url it will use by calling tweets.url()
.