扩展主干模型保存

Extend Backbone model save

本文关键字:保存 模型 扩展      更新时间:2023-09-26

扩展 model.save方法的最佳方法是什么?

我需要添加新方法来将相同的数据发布到后端,即:played方法应该请求(通过 POST)apiurl/model/:id/played

例如:

var Game = Backbone.Model.Extend({
   baseUrl: '/games/',
   played: function(){
      this.url = this.baseUrl + this.id + '/played' 
      this.save();
   }
}); 
var game = new Game({id:3234});  //is only an example, instances are created before previuosly
game.played();

这种方式有效,但请求是 GET。此外,如果此save()不发送请求中的所有属性,那就完美了。

添加信息:由于我必须与跨域 API 交互,因此我扩展了同步方法以使用 JSONP。此外,我还添加了一些安全说明。

//backbone sync
Backbone._sync = Backbone.sync;
Backbone.sync = function(method, model, options) {
    //network
    options.timeout = 10000;
    options.dataType = "jsonp";  
    //security
    if(_conf.general.accessToken){
        var ak = _conf.general.accessToken, 
        url = model.url,
        linker = url.indexOf('?') === -1 ? '?':'&';
        model.url = url + linker + 'accessToken=' + ak+'&callback=';    
    }
    //error manager
    var originalError = options.error || function(){};
    options.error = function(res){
        originalError(res.status, $.parseJSON(res.responseText));
    };
    //call original Method 
    Backbone._sync(method, model, options);  
};
Backbone 的

保存和获取方法只是调用 Backbone.sync 方法,而该方法又只是 ajax 调用的包装器。 您可以使用 save 函数传入 ajax 参数,而无需实际扩展它。 基本上最终是这样的:

game.save({attributes you want to save}, {type:'POST', url: 'apiurl/model/:id/played'});

不过,您每次都必须执行此操作,因此最好为您的模型扩展 Backbone.sync。

Backbone

网站有一些关于我所说的信息,就Backbone同步和保存ajax选项而言。我也看到了一些关于扩展同步的示例,但目前我似乎无法追踪它们。