Backbone覆盖同步和更新模型

时间:2015-03-11 19:59:51

标签: javascript backbone.js parse-platform

我编写了下面的函数来更新模型,但它需要一个访问令牌,所以我想覆盖同步函数,但我总是有这个错误:

 PUT https://api.parse.com/1/users/ZT0w7QdYvk 400 (Bad Request)

所以我认为也许同步不能正确覆盖或者可能是其他一些错误。

updateUser: function(){

      var sync = Backbone.sync;
      var parseSessionToken = window.localStorage.getItem('parseSessionToken');
      Backbone.sync = function(method, model, options) {
           options.beforeSend = function(xhr) {
            xhr.setRequestHeader('X-Parse-Application-Id', 'uR2Omi3B**ed9thVESad');
            xhr.setRequestHeader('X-Parse-REST-API-Key', 'GbwUqq**Fxzbd1tFCXje');
            xhr.setRequestHeader('X-Parse-Session-Token', parseSessionToken);
        };


        sync(method, model, options);

          }









    var targa = $('#targa').val();
    var auto = $('#auto').val();


    var users = new Utenti();

    users.fetch({
     success: function () {

    var user = users.get( window.localStorage.getItem('parseId'));
    console.log(targa);
    user.set({'targa': targa,'auto':auto});
    console.log(user);
    user.save();


        }
      });




         },

1 个答案:

答案 0 :(得分:0)

您可以基于每个型号/集合覆盖同步。我不会覆盖基础Backbone.sync

var MyModel = Backbone.Model.extend({
  sync: function (method, model, options) {
    options.header = _.extend(options.header || {}, {
      'X-Parse-Application-Id': 'uR2Omi3B**ed9thVESad',
      'X-Parse-REST-API-Key': 'GbwUqq**Fxzbd1tFCXje',
      'X-Parse-Session-Token': parseSessionToken
    });
    return Backbone.Model.prototype.sync.call(this, method, model, options);
  }
});