Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify url and header in backbone to use crud method on my model?

Tags:

backbone.js

i need to make request on server that needs of particulary api key and i need to use the crud method tu update my model and as soon as...

For example i have this code in ajax to get element from server:

 function getapi() {

$.ajax({
    url: 'https://api.parse.com/1/classes/autolavaggi/QSfl*****',
    type: 'GET',
    dataType: 'json',

    success: function(obj) { 

        alert("nome autolavaggio "+obj.nome);

    },
    error: function() {
        alert('Errore');


    },
    beforeSend: setHeader
});
}  

    //GET GET  GET  GET  GET GET  GET  GET  Header Header Header Header
    function setHeader(xhr) {
xhr.setRequestHeader('X-Parse-Application-Id', 'aqLJlmE2rRXBOy***************');
xhr.setRequestHeader('X-Parse-REST-API-Key', 'gvT2Isd5vAvjgq*****************');
}

How can i do to assign this particular ajax call to crud method save,fetch or another??

like image 343
Stefano Maglione Avatar asked Jul 13 '12 16:07

Stefano Maglione


1 Answers

Each of the crud methods accept an options hash that will get forwarded to the ajax call. In the case of a collection fetch:

var Model = Backbone.Model.extend({});
var Collection = Backbone.Collection.extend({
  model: Model,
  url: 'https://api.parse.com/1/classes/autolavaggi/QSfl*****'
});

var setHeader = function (xhr) {
  xhr.setRequestHeader('X-Parse-Application-Id', 'aqLJlmE2rRXBOy***************');
  xhr.setRequestHeader('X-Parse-REST-API-Key', 'gvT2Isd5vAvjgq*****************');
}

var collection = new Collection();
collection.fetch({ beforeSend: setHeader });

Alternatively, override sync:

var sync = Backbone.sync;
Backbone.sync = function(method, model, options) {
  options.beforeSend = function (xhr) {
    xhr.setRequestHeader('X-Parse-Application-Id', 'aqLJlmE2rRXBOy***************');
    xhr.setRequestHeader('X-Parse-REST-API-Key', 'gvT2Isd5vAvjgq*****************');
  };

  // Update other options here.

  sync(method, model, options);
};
like image 169
jmconrad Avatar answered Nov 26 '22 14:11

jmconrad