Backbone JS 处理保存模型?
使用 Backbone,我可以获取
如下所示的集合,并为每条记录呈现一个 Backbone 视图:
Person = Backbone.Model.extend({});
var PersonCollection = Backbone.Collection.extend({
model: Person,
url: '/home/people/'
});
当我像下面这样使用 Backbone 启动一个新人时,它不是应该已经处理了 .save()通过发布到上述集合中定义的 URL 来实现功能吗?
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
Using Backbone I can fetch
the Collection like below and render a Backbone View for each record:
Person = Backbone.Model.extend({});
var PersonCollection = Backbone.Collection.extend({
model: Person,
url: '/home/people/'
});
When I spin up a new person using Backbone like below, isn't it supposed to already handle the .save() functionality by posting to the URL defined in the above collection?
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看起来一种方法是使用当前集合和
create
来处理将其添加到集合中并保存它源如下。 Create 不在集合中,因此它将 Models 集合设置为
this
然后,一旦 Save it 成功,它将 Model 添加到您的集合中。因此它将模型传递给 getUrl,getUrl 查看模型上的 URL 属性,模型又将集合再次传递给 getUrl...这样我们就不必重新定义 URL...Looks like an approach is to use the current collection and
create
which handles adding it to the collection and saving itThe source is below. Create is off the collection, so it sets the Models collection to
this
Then once the Save it success it adds Model to your collection. So it passes the model to getUrl, the getUrl looks at the URL property on the model, which in turn passes the collection to getUrl again... that way we don't have to redefine URL...您只需设置集合
Person.collection = PersonCollection
现在它就会神奇地知道 url。
You can just set the collection
Person.collection = PersonCollection
Now it will magically know the url.
根据Backbone.sync中的backbone.js代码,情况似乎并非如此。也许文档是旧的或不正确的。代码如下:
这向我表明该模型需要自己的 url。所以你应该这样做:
According to the backbone.js code in Backbone.sync, this does not seem like the case. Perhaps the documentation is old or not correct. The code reads:
which suggests to me that the model needs its own url. So you should just do this: