简体   繁体   English

扩展Backbone模型保存

[英]Extend Backbone model save

What is the best way to extend the model.save method ? 扩展 model.save方法的最佳方法是什么?

I need to add new methods to post same data to backend. 我需要添加新方法将相同的数据发布到后端。 ie: played method should request (by POST) to apiurl/model/:id/played 即: played方法应该请求(通过POST) apiurl/model/:id/played

eg: 例如:

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();

This way is working but the request is a GET. 这种方式有效,但请求是GET。 In addition, it would be perfect if this save() did not send all the attributes in the request. 此外,如果此save()未发送请求中的所有属性,那将是完美的。

Adding information: As I have to interact with cross domain api, I've extended the sync method in order to work with JSONP. 添加信息:由于我必须与跨域api进行交互,因此我扩展了同步方法以使用JSONP。 Moreover, I've added some security instructions. 此外,我添加了一些安全说明。

//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's save and fetch methods just make calls to the Backbone.sync method, which in turn is just a wrapper for an ajax call. Backbone的save和fetch方法只调用Backbone.sync方法,后者又只是ajax调用的包装器。 you can pass in ajax parameters using the save function without having to actually extend it. 您可以使用save函数传递ajax参数,而无需实际扩展它。 basically ends up being something like this: 基本上最终是这样的:

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

You would have to do this every time though so it is probably better practice to extend Backbone.sync for your model. 您每次都必须这样做,因此为您的模型扩展Backbone.sync可能是更好的做法。

The Backbone website has a bit of information about what I'm talking about as far as the Backbone sync and save taking ajax options. Backbone网站提供了一些关于我正在讨论的关于Backbone同步和保存ajax选项的信息。 There are also a few examples I've seen on extending sync but I can't seem to track them down at the moment. 我在扩展同步时也看到了一些例子,但我现在似乎无法追踪它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM