1

我琐碎的 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 } );
4

1 回答 1

3

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

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

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

当我想使用列表引导 Backbone.PageableCollection 时,我刚刚处理了一个我认为类似于此的情况。该修复程序无论如何都违反了 Backbone.Collection,但这是我可以使用的快速解决方案。我不知道为什么如果我在 .extend(options) 中为 Backbone.PageableCollection 传递 #url 它不会到达模型,但是如果我用 url 初始化它,那么 url 会像所有模型一样传递给模型实例获取不附加 id 的 #url{string} 。经过一些搜索/修改后,我决定只给出模型定义#urlRoot。

Backbone.PageableCollection.extend({
   model : Backbone.Model.extend({
      urlRoot : '...'
   })
});
于 2015-02-18T15:43:15.350 回答