Mar*_*iry 3 javascript backbone.js
什么是最好的方式扩展的model.save
方法?
我需要添加新方法将相同的数据发布到后端.ie: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();
Run Code Online (Sandbox Code Playgroud)
这种方式有效,但请求是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);
};
Run Code Online (Sandbox Code Playgroud)
小智 5
Backbone的save和fetch方法只调用Backbone.sync方法,后者又只是ajax调用的包装器.您可以使用save函数传递ajax参数,而无需实际扩展它.基本上最终是这样的:
game.save({attributes you want to save}, {type:'POST', url: 'apiurl/model/:id/played'});
Run Code Online (Sandbox Code Playgroud)
您每次都必须这样做,因此为您的模型扩展Backbone.sync可能是更好的做法.
Backbone网站提供了一些关于我正在讨论的关于Backbone同步和保存ajax选项的信息.我在扩展同步时也看到了一些例子,但我现在似乎无法追踪它们.