I'm not sure if this is the proper way to do things, but it works this way, so here's my solution. I override fetch and never call the default fetch method. Instead I make an ajax call in the fetch method, and have an onResponse
method that handles the response, creating the models (Yelp Businesses) for the response. Hope this helps anyone in the same position.
LOAF.YelpList = Backbone.Collection.extend({
model: LOAF.Business,
url: 'http://api.yelp.com/v2/search?',
fetch: function(options) {
var accessor, message, parameterMap, parameters;
if (!options) {
options = {};
}
accessor = {
consumerSecret: LOAF.auth.consumerSecret,
tokenSecret: LOAF.auth.accessTokenSecret
};
parameters = [];
parameters.push(['callback', 'cb']);
parameters.push(['oauth_consumer_key', LOAF.auth.consumerKey]);
parameters.push(['oauth_consumer_secret', LOAF.auth.consumerSecret]);
parameters.push(['oauth_token', LOAF.auth.accessToken]);
parameters.push(['oauth_signature_method', 'HMAC-SHA1']);
parameters.push(['location', "New York City"]);
message = {
'action': this.url,
'method': 'GET',
'parameters': parameters
};
OAuth.setTimestampAndNonce(message);
OAuth.SignatureMethod.sign(message, accessor);
parameterMap = OAuth.getParameterMap(message.parameters);
parameterMap.oauth_signature = OAuth.percentEncode(parameterMap.oauth_signature);
options.url = this.url;
options.data = parameterMap;
options.cache = true;
options.dataType = 'jsonp';
options.jsonpCallback = 'cb';
options.success = this._onResponse;
options.context = this;
return $.ajax(options);
},
_onResponse: function(data, textStats, xhr) {
debugger;
var _this = this;
return _.each(data.businesses, function(business) {
var busModel;
if (!_this.get(business.id)) {
busModel = new LOAF.Business(business);
return _this.add(busModel);
}
});
}
});
Two things to note:
- The initial code would have worked but the consumerSecret was spelled wrong, resulting in improper OAuth calls. That's why I was getting a 400 error.
- Even if you fix this, there's the problem of Cross-Origin calls. Switching to the AJAX method I used alleviates this problem. However, there may exist a way to fix this more native to Backbone. For the time-frame of my project, this would not do.