我的模特:
var Backbone = require('backbone');
module.exports = Backbone.Model.extend({
idAttribute: '_id',
defaults: {
id: 0,
description: '',
amount: 0,
dateEntry: new Date(),
positive: false
},
url: '/api/transactions'
});
我的收藏:
var Backbone = require('backbone');
var Transaction = require('../models/Transaction')
var TransactionCollection = Backbone.Collection.extend({
model: Transaction,
url: '/api/transactions',
initialize: function() {
this.hasNextPage = false;
this.filter = 'all';
},
parse: function(response) {
this.hasNextPage = response.hasNextPage;
this.balance = response.balance;
return response.transactions || [];
}
});
module.exports = new TransactionCollection();
我有许多项目视图,每个视图都显示其模型数据(事务)。
在每个项目视图中都有"删除"按钮触发:
delete: function() {
console.log("Remove:: ");
console.log(this.model.toJSON());
this.model.destroy();
}
查看控制台,我看到对/ api / transactions /
的REST DELETE调用不应该是/ api / transaction / model_id 吗?实际上,我在服务器端(NodeJS)看到空的req.body和req.query。
浏览器控制台记录:
[Log] Object (app.js, line 20298)
__v: 0
_id: "5421da84c6fd7c91060ba405"
amount: 1200
category: Object
dateAdded: "2014-09-23T20:39:32.905Z"
dateEntry: "2014-06-17T22:00:00.000Z"
description: "Example!"
id: 0
positive: true
user: "53fbb34fb91a922f03be61f8"
__proto__: Object
交易数据来自MongoDB,因此拥有 _id 属性。
我怀疑这是我的问题的原因。如何让我的Backbone应用程序调用正确的DELETE URL?
答案 0 :(得分:1)
在你的模型中,当你应该覆盖url属性时,你将覆盖urlRoot属性
//intercept the request for testing.
$.mockjax({
// matches /api/transactions/abCD1234
url: /^\/api\/transactions\/([0-9a-zA-A]+)$/,
urlParams: ['id'],
response: function (settings) {
var id = settings.urlParams.id;
$('body').append(id);
}
});
var yourModel = Backbone.Model.extend({
idAttribute: '_id',
defaults: {
id: 0,
description: '',
amount: 0,
dateEntry: new Date(),
positive: false
},
//This is the property that sets the "base" of all your REST urls
urlRoot: '/api/transactions'
});
var yourInstance = new yourModel({
_id:'5421da84c6fd7c91060ba405',
amount: 1200,
dateAdded: "2014-09-23T20:39:32.905Z",
dateEntry: "2014-06-17T22:00:00.000Z",
description: "Example!",
id: 0,
positive: true,
user: "53fbb34fb91a922f03be61f8"
});
yourInstance.destroy();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/1.5.3/jquery.mockjax.min.js"></script>