简体   繁体   中英

How can I get a collection of models from the server using Backbone.js?

I can't figure out the correct way to get a collection of models from the server into my Backbone Collection, assuming I don't want all the models from the DB, but rather a group of models (filtered by a specific model property).

The only way I can figure out is to override Fetch and use the function's "options" parameter to pass a filter definition to my Backbone.Sync function.

Is there a better way?

3 most used ways to set a collection, are

  1. bootstrapping models in the page, and then loading them with Collection.reset();

     // you can print this trough serverside in your view, (you are bootstrapping these models) var bsModels = [{'name': 'name1'},{'name': 'name3'},{'name': 'name2'}]; // in your code you can use that bootstrapped data via the reset method. var myModel = Backbone.Model.extend({}); var myCollection = Backbone.Collection.extend({ model: myModel }); myCollection.reset(bsModels); 
  2. you can use the fetch, but it would load any and all methods, unless you override the fetch method

  3. a third option is to write your own ajax call, fetching the correct amount of models, and using the same technique as in #1, using Collection.reset(data);

Sure, there's a better way! You can pass query params to your fetch() call. All of the options passed to fetch go straight into $.ajax() . So for example:

myCollection.fetch({
  data: {
    search: "boo",
    limit: "20"
  }
}

Since this turns into a GET request, those will be appended to the query string, and you can parse them on the server and return the appropriate items for the collection.

If you're feeling fancy, you can redefine fetch() for a specific type of collection so that it always posts the appropriate query params.

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