Backgrid REST设计:ID不会自动在URL中传递

时间:2013-07-12 14:50:38

标签: javascript rest backbone.js backgrid

我的琐碎CRUD REST设计如下所示:

create: [USERID]/weights/
read:   [USERID]/weights/[ITEMID]
update: [USERID]/weights/[ITEMID]
delete: [USERID]/weights/[ITEMID]

我尝试过backgrid和methodToURL。我所取得的成就是:

create: [USERID]/weights/
read:   [USERID]/weights/
update: [USERID]/weights/
delete: [USERID]/weights/

即。根本没有传递ITEMID。即使没有methodToURL backgrid也不会传递ITEMID。现在我迷路了。有什么建议吗?

这是我的意思。尝试:

var Weight = Backbone.Model.extend({
    urlRoot: "weights",
    initialize: function() {
        Backbone.Model.prototype.initialize.apply(this, arguments);
        this.on("change", function(model, options) {
            console.log("Saving change");
            if (options && options.save === false)
                return;
            model.save();
        });
    },

    methodToURL: {
        'read': '/' + sesUserId +'/weights/',
        'create': '/' + sesUserId +'/weights/',
        'update': '/' + sesUserId +'/weights/',
        'delete': '/' + sesUserId +'/weights/'
    },
    sync: function(method, model, options) {
        options = options || {};
        options.url = model.methodToURL[method.toLowerCase()];
        Backbone.sync(method, model, options);
    }    
});


var PageableWeightTable = Backbone.PageableCollection.extend({
    model: Weight,
    url: '/' + sesUserId +'/weights/',
    state: {
        pageSize: 10
    },
    mode: "client" // page entirely on the client side
});

var weightTable = new PageableWeightTable();
var grid = new Backgrid.Grid({
columns: [{
        // name is a required parameter, but you don't really want one on a select all column
        name: "",
        // Backgrid.Extension.SelectRowCell lets you select individual rows
        cell: "select-row",
        // Backgrid.Extension.SelectAllHeaderCell lets you select all the row on a page
        headerCell: "select-all"
    }].concat(columns),
    collection: weightTable
});

var $divWeightTable = $("#divweighttable");
$divWeightTable.append(grid.render().$el);

var paginator = new Backgrid.Extension.Paginator({
    collection: weightTable
});

$divWeightTable.append(paginator.render().$el);

weightTable.fetch( { reset: true } );

1 个答案:

答案 0 :(得分:3)

看起来你缺少idAttribute。看来模型没有检测到它的id。你在用mongodb吗?如果是这样,那么idAttribute应该是_id,如:

Backbone.Model.extend({
   idAttribute : "_id"
});

如果不是,那么您应该使用映射到主键的其他内容(如果它不是'id')。

当我想使用列表来引导Backbone.PageableCollection时,我刚刚处理了一个我认为类似的情况。该修复违反了Backbone.Collection,但它是我可以使用的快速解决方案。我不知道为什么如果我在.extend(选项)中传递#url为Backbone.PageableCollection它没有到达模型但是如果我用url初始化它,则url会被传递给模型实例,因此所有模型得到#url {string},不附加ids。经过一些搜索/修改后,我决定只给出模型定义#urlRoot。

Backbone.PageableCollection.extend({
   model : Backbone.Model.extend({
      urlRoot : '...'
   })
});