简体   繁体   中英

Understanding backbone.js collections

I'm trying to understand how backbone.js collections work. Assuming I have a database of, lets say users. I want a simple crud on a user.

What is the right way? To define users collection, and then access to the required model within the collection scope? Or is it 100% legit to override model's url method for REST CRUD for a single user?

If the first option is the correct one, how should I handle collection lazy initialization? And if the second one is alright, what will happen if I'll try to show, for example, the recent users that logged in (that means I'll have to use a collection, and overridden url property may affect this).

I feel like I'm missing the link in the chain, but can't find it in the documentation.

When working with a set like this, you will typically load the data via a Backbone.Collection and manipulate individual records via the Backbone.Model instances inside the collection. In the case of users, the currently-logged in user will be a Model, but if you are viewing and working with the other data in the users table, that will be loaded via a Collection.

  • Create 1 user -> use Backbone.Model.save() -> POST /user
  • Read 1 user -> use Backbone.Model.fetch() -> GET /user/42
  • Update 1 user -> use Backbone.Model.save() -> PUT /user/42
  • Delete 1 user -> use Backbone.Model.destroy() -> DELETE /user/42

  • Load a batch of users -> use Backbone.Collection.fetch() -> GET /users

  • Load a batch of users with a sort order (by recent login for example) -> use Backbone.Collection.fetch() with the proper query string in the URL -> GET /users?order_by=login

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM