Ale*_*lls 7 javascript backbone.js
在Backbone模型中,我们有url和urlRoot属性:
url: function(){
return '/jobs'
},
urlRoot: function () {
return '/jobs'
},
Run Code Online (Sandbox Code Playgroud)
但是我想在URL中添加params或查询参数,具体取决于GET,POST,PUT,DELETE等请求的类型.
所以我想做这样的事情:
url: function(type, opts){ //type and opts arguments are not available in Backbone, I just made them up for this example
var url = '/jobs';
switch (type) {
case 'GET':
break;
case 'POST':
break;
case 'PUT':
url = url + '?optimisticDelete=' + opts.optimisticDelete;
break;
case 'DELETE':
url = url + '?upsert=' + opts.upsert;
break;
default:
throw new Error('no match');
}
return url;
},
Run Code Online (Sandbox Code Playgroud)
有没有一个很好的方法来完成这样的事情?
默认情况下,Backbone模型和集合委托给与Backbone.sync服务器交互的函数.这是您可以访问HTTP方法的范围,如示例中所示.您可以覆盖模型或集合上的同步功能以自定义此行为.退房的文档和源代码的Backbone.sync和为jQuery.ajax,其Backbone.sync使用.
我有一段时间没有触及Backbone或JavaScript,但我想它会看起来像这样(这基本上是伪代码,不要指望它按照书面形式工作):
sync: function (method, model, options) {
// method corresponds to the HTTP verb ("type" in your example)
switch (method) {
// ...build the correct url like in your example...
}
options = options || {};
options.url = url; // tack correct url onto options object
return Backbone.sync.apply(this, [method, model, options]);
}
Run Code Online (Sandbox Code Playgroud)
它很可能需要更多的摆弄,但希望它能够解决问题.
| 归档时间: |
|
| 查看次数: |
952 次 |
| 最近记录: |