Backbone.js 在 Restful 模型上使用非 Restful 操作
我有一个常规的 Restful 模型,我可以获取、创建、删除和更新它。最重要的是,我想对该模型调用特殊操作,例如change_password。
常规 RESTful 路线是传统的 Rails 3 路线:
fetch => GET /api/models/:id
save => PUT /api/models/:id
create => POST /api/models
destroy => DELETE /api/models/:id
但是,除此之外,我还有特殊操作:
changePassword => GET /api/models/:id/change_password
activate => GET /api/models/:id/activate
等等。
我需要在模型上设置什么,以便它识别这些新操作,以及如何将调用包装到模型方法中?
I have a regular restful model that I do get, create, delete and update. On top of that, I'd like to call special actions on that model, like change_password.
The regular RESTful routes are traditional Rails 3 routes:
fetch => GET /api/models/:id
save => PUT /api/models/:id
create => POST /api/models
destroy => DELETE /api/models/:id
But, on top of those, I have special operations:
changePassword => GET /api/models/:id/change_password
activate => GET /api/models/:id/activate
And so on.
What do I need to setup on the model, so it recognizes those new actions, and how to wrap the calls into model methods?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
向模型添加新方法相当简单 - 只需在
.extend()
中指定新方法即可。您必须自己编写其中的一些代码,但您可以利用现有的机制,例如Backbone.sync
(主要只是$.ajax()
的包装器)和模型的现有url
属性:就像注释一样,从 REST 角度来看,您的
changePassword
和activate
操作不应该是GET 方法 - 所有 GET 方法都应该是幂等的。这不仅仅是 RESTifarianism,它是一个好主意 - 您最终可能会缓存这些 URL(因此什么也不会发生)或意外多次点击它们(通常需要用户通过 POST 请求进行确认)。如果可以的话,拨打这些 POST 电话。It's fairly simple to add new methods to a Model - just specify the new methods in
.extend()
. You have to code some of this yourself, but you can take advantage of existing machinery likeBackbone.sync
(mostly just a wrapper around$.ajax()
) and the Model's existingurl
property:Just as a comment, from a REST perspective, your
changePassword
andactivate
operations should not be GET methods - all GET methods should be idempotent. This is not just RESTifarianism, it's a Good Idea - you could end up caching these URLs (so nothing happens) or hitting them multiple times by accident (usually requiring user confirmation with a POST request). Make these POST calls if you can.我建议如果可能的话添加一个密码模型/控制器,您可以在其中调用保存来更改密码。这遵循 REST 标准,并内置于 Backbone.js 的功能中。
如果这不是一个选项,以下是 CoffeeScript 示例,请将其添加到您的模型中:
I would advise that if possible add a Password model/controller where you can call save on to change the password. This follows the REST standards and is built in functionality of Backbone.js
If that's not an option, the following is a CoffeeScript example, add this to your model: