Models
AJAX Abstraction for a Single Resource
AJAX Abstraction for a Single Resource
The initialize()
method is called at the end of model instantiation, and is useful for storing data that other methods will need.
The default implementation looks like this:
initialize: function(attributes, options) {
// does nothing
},
A common use for this method is storing variables that will be needed 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/1
when fetching or updating data.
The code below shows how you can use initialize()
to accomplish this:
import { Model } from 'lore-models';
const Tweet = Model.extend({
urlRoot: 'http://localhost:1337',
initialize: function(attributes, options){
this.user = options.user;
},
url: function() {
return `${this.urlRoot}/users/${this.user}/tweets/${this.attributes.id}`
}
})
const tweet = new Tweet({
id: 1
}, {
user: 1
})
tweet.fetch()
In the code above, we're providing a second argument to new Tweet()
, and that additional information is passed to initialize()
as options
, where we save the id for the user
.
Then we override the url()
function to compose the final nested URL using the user
, along with the id
of the tweet.
When we call tweet.fetch()
it will make an API call to http://localhost:1337/users/1/tweets/1
, and you can confirm the url it will use by calling tweet.url()
.