骨干js批处理保存
我们正在保存模型的集合,但主干似乎想要一个接一个地执行这些操作。这可能成本高昂并且需要一段时间才能完成,如果用户刷新或离开页面中间过程,可能会导致数据无法保存。
有没有办法让 Backbone 将它们作为数组发送出去?
我该怎么做?
进行保存的代码:
_(this.models).each(
function(guest) {
if (tid == guest.get('tableId') || guest.get('tableId') == null) {
guest.set({ tableId: tid });
guest.save();
}
}
);
We're saving a collection of a model but backbone seems to want to do these one after the other. This can be expensive and takes a while to complete which can lead to data not being saved if the user refreshes or navigates away from the page mid process.
Is there a way to get Backbone to send them off as an array?
How would I do this?
code that does the saving:
_(this.models).each(
function(guest) {
if (tid == guest.get('tableId') || guest.get('tableId') == null) {
guest.set({ tableId: tid });
guest.save();
}
}
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我已经考虑这个问题有一段时间了... REST 没有定义多个项目的推送(据我所知),因此您必须编写一些自定义内容才能实现它。
我认为最好的方法是在后端创建一个自定义路由,即
/entities
路径的PUT
,就像现有的GET
这实际上只是一个“索引”。它需要一个 JSON 集合,就像 GET 现在返回一个 JSON 集合一样。然后,您需要重写
Backbone.Collection
以包含save
函数。由于 Backbone.sync 只有四个动词(创建、更新、删除、读取),因此您可能想要进行“更新”,但您可能需要编写一些代码,以便序列化您的集合到 JSON 集合并将其放入正文中。我希望在Backbone.sync
中进行一些覆盖,或者只是在新的Backbone.Collection.save
中对$.ajax
进行自定义调用功能。至少,这就是我攻击它的方式。 :)
I've been thinking about this for a while... REST doesn't define a push of multiple items (that I am aware of) so you will have to write some custom stuff to make it happen.
I think the best way to go is to create a custom route on the back-end that is is a
PUT
to your/entities
path, much like the existingGET
which is really just an "index". It would take a JSON collection much like the GET returns a JSON collection now.Then, you would need to override
Backbone.Collection
to include asave
function. SinceBackbone.sync
only has the four verbs (create, update, delete, read), you would want to do an "update" but you will probably have to write a bit of code so serialize your collection to a JSON collection and put it in the body. I'd expect a bit of overriding inBackbone.sync
or just a custom call to$.ajax
in your newBackbone.Collection.save
function.At least, that is how I'd attack it. :)