Backbone JS Handle Save Model?

时间:2011-04-30 17:35:36

标签: backbone.js

使用Backbone我可以fetch如下所示收集并为每条记录渲染一个Backbone View:

Person = Backbone.Model.extend({});

var PersonCollection = Backbone.Collection.extend({

    model: Person,
    url: '/home/people/'
});

当我像下面那样使用Backbone启动一个新人时,是否应该通过发布到上述集合中定义的URL来处理.save()功能?

var p = new Person({ Name: 'Andrew', Age: 24 });
p.save();
// Uncaught Error: A 'url' property or function must be specified
// I thought it was supposed to use the Collection's URL?
// I can get around this by explicitly setting p.URL but doesn't seem right

3 个答案:

答案 0 :(得分:7)

看起来一种方法是使用当前集合和create来处理将其添加到集合并保存它

this.people.create(p);

来源如下。 Create不在集合中,因此它将Models集合设置为this然后,一旦Save it success,它就会将Model添加到您的集合中。因此它将模型传递给getUrl,getUrl查看模型上的URL属性,然后再将集合传递给getUrl ......这样我们就不必重新定义URL ...

create : function(model, options) {
  var coll = this;
  options || (options = {});
  if (!(model instanceof Backbone.Model)) {
    model = new this.model(model, {collection: coll});
  } else {
    model.collection = coll;
  }
  var success = function(nextModel, resp) {
    coll.add(nextModel);
    if (options.success) options.success(nextModel, resp);
  };
  return model.save(null, {success : success, error : options.error});
},

答案 1 :(得分:6)

您只需设置集合

即可

Person.collection = PersonCollection

现在它会神奇地知道网址。

答案 2 :(得分:5)

根据Backbone.sync中的backbone.js代码,情况似乎并非如此。也许文档陈旧或不正确。代码如下:

// Helper function to get a URL from a Model or Collection as a property
// or as a function.
var getUrl = function(object) {
  if (!(object && object.url)) throw new Error("A 'url' property or function must be specified");
  return _.isFunction(object.url) ? object.url() : object.url;
};

这告诉我该模型需要自己的网址。所以你应该这样做:

Person = Backbone.Model.extend({
  url: function() {
    if (this.isNew()) return '/home/people/';
    return '/home/whatever-this-route-would-be';
  }
});