Backbone集合中的自定义非REST方法

时间:2014-03-15 04:37:59

标签: javascript jquery backbone.js

这是我的Backbone系列:

var TodoList = Backbone.Collection.extend({

        // Reference to this collection's model.
        model: Todo,

        url: function () {
            return 'api/todos';
        },

        // Filter down the list of all todo items that are finished.
        done: function () {
            return this.filter(function (todo) { return todo.get('done'); });
        },

        // Filter down the list to only todo items that are still not finished.
        remaining: function () {
            return this.without.apply(this, this.done());
        },

        // We keep the Todos in sequential order, despite being saved by unordered
        // GUID in the database. This generates the next order number for new items.
        nextOrder: function () {
            if (!this.length) return 1;
            return this.last().get('order') + 1;
        },

        // Todos are sorted by their original insertion order.
        comparator: function (todo) {
            return todo.get('order');
        },

        addToDo: function (opts) {
            var model = this;
            opts.url = model.url() + '/AddToDo'

            // add any additional options, e.g. a "success" callback or data
            _.extend(options, opts);
            return (this.sync || Backbone.sync).call(this, null, this, options);
        }

    });

这很好用,我可以点击我的URL端点。但是,问题在于Backbone集合中定义的内置create,一旦调用create,模型就会自动添加到集合中。使用我的自定义方法addToDo,可以成功添加待办事项,但除非我刷新页面,否则我无法在视图中看到它。

我错过了什么?任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:1)

.create是model.savecollection.add周围的句法糖 如果您的模型是以不同的方式创建的,则需要将模型上的sync方法覆盖为:

sync: function (method, model, options) {
  options || (options = {});
  if (method === 'create') {
    options.url = _.result(model, 'url') + '/AddToDo';
  }
  return Backbone.Model.prototype.sync.call(this, method, model, options);
}