Reputation: 4028
I have been looking at this documentation :
http://addyosmani.github.io/backbone-fundamentals/#backbones-sync-api
To try and figure out how to make a HTTP POST request to get some JSON data to load into my model. Sadly the web services are not RESTful, so I am doing a POST request, when in fact it should be a GET request. Such is life...
I have ended up with the following result but I am not sure if this is the correct way or if there is an easier way altogether and because I am not strictly using REST pattern I can't seem to find anyway to tie up my services with Backbone pattern.
define([
'underscore',
'backbone',
], function (_, Backbone)
{
'use strict';
//model class declaration
var LocationsModel = Backbone.Model.extend({
locations : null, //this stores the json data of buildings and locations
//url for http post to get location data
url: '/locations',
//http request settings
requestType: 'POST',
requestContent : 'application/json; charset=utf-8',
requestBody: { "lastRefreshedDateTime": "2015-04-01T08:18:06.000+00:00", "uid": "12356789" },
requestData: 'json',
/**
@name constructor
@method initialise
**/
initialize: function (xhr)
{
this.doPOST();
},
/**
@name doPOST
@method doPOST
@summary uses AJAX HTTP POST to fetch data from EAS
**/
doPOST: function ()
{
$.ajax({
type: this.requestType,
data: this.requestBody,
contentType: this.requestContent,
dataType: this.requestData,
url: "http://" + window.location.host + this.url,
success: function (result)
{
this.locations = result;
},
error: function (jqXHR, textStatus, errorThrown)
{
//TODO - load cached JSON of buildings and locations
},
});
}
});
return LocationsModel;
});
So this code is essentially
Is there anyway I can abstract this more?
Upvotes: 2
Views: 165
Reputation: 22817
Override .fetch()
:
var RestlessModel = Backbone.Model.extend({
defaults: function(){
return {
locations: []
}
},
//url for http post to get location data
url: '/locations',
//http request settings
fetchOverride: {
type: 'POST',
contentType : 'application/json; charset=utf-8',
data: JSON.stringify({ "lastRefreshedDateTime": "2015-04-01T08:18:06.000+00:00", "uid": "12356789" }),
dataType: 'json',
},
fetch: function(options){
options = _.extend(options || {}, this.fetchOverride);
Backbone.Model.prototype.fetch.call(this, options);
}
});
See fiddle ^^
In case you need to process the request response, override .parse()
.
Upvotes: 2