Models
AJAX Abstraction for a Single Resource
AJAX Abstraction for a Single Resource
The sync()
method is a wrapper over the sync function, and allows you to modify how server calls are made for the model.
The default implementation looks like this:
import { sync } from 'lore-models';
...
sync: function(method, model, options) {
return sync(method, model, options);
},
One use case for this method is to modify the data before it's sent to the API. For example, let's say the tweets in our application currently use an attribute named text
to describe what the user said, but the API underwent a change recently and that property is now called message
.
If we send the text
attribute to the API, it will ignore the attribute, because it doesn't recognize it. So we need to transform text
to message
before making the API call.
We can do that using this code:
import { sync } from 'lore-models';
...
sync: function(method, model, options) {
if (method === 'create' || method === 'update') {
// copy the model's attributes
const data = _.assign({}, model.attributes);
// replace 'text' with 'message'
data.message = data.text;
delete data.text;
// provide the new 'data' through 'options', which will be sent to the API
return sync(method, model, _.assign({}, options, {
data: data
}));
}
return sync(method, model, options);
},
In the code above, we're checking the method
to see whether we're performing a create
or update
action.
If we are, then we're coping the model's attributes, replacing text
with message
, and then providing the new data to sync
, so that it will be sent to the API instead of the models normal attributes.
A simpler version of the code above would look like this:
import { sync } from 'lore-models';
...
sync: function(method, model, options) {
if (method === 'create' || method === 'update') {
model.attributes.message = model.attributes.text;
}
return sync(method, model, options);
},
The difference is that in this code, we're actually modifying the attributes of the model, whereas the previous code only modify the network request.