0

I have limited knowledge of Backbone.js and I am having some troubles in applying the concepts of Model and Collections for the project.

On the server/database side, it is designed that: users can CRUD a list of Category's which is like a Backbone.js's Collections. Under Category, users can CRUD Worksheets. Under Worksheet, users can CRUD Items.

Should I have Worksheet as a Collection or a Model? Or can I have a Collection of Items inside a Model of Worksheet? If so, how can I do that?

Also, apart from the usual CRUD RESTful operations, what is the best way to implement ordering/sorting of Models within a Collection using Backbone.js with REST? I want the Items to be able for users to sort within the Worksheet. I've read a few Backbone.js tutorials, they mostly cover the CRUD operations and not something else like sorting.

May be I have missed something but I just don't understand the point of Collection, there is a fetch method under Collection but can I fetch all Models under one particular Collection using a collection id? Tutorials don't cover something like this....

user2526586
  • 972
  • 2
  • 12
  • 27
  • Backbone doesn't support nested structures out of the box, you might want to look into something like http://backbonerelational.org/#examples – T J May 30 '18 at 13:17

1 Answers1

0

Keep in mind, the point of using the model/collection classes are to take advantage of their methods, vs creating a simple array. So with event handling for example, you can listen to events on a single model, OR you can listen to an entire collection of models. And then update the server as needed.

If you have multiple worksheets, then worksheets can be a new collection as well. Which means each worksheet will be a backbone model.

Sorting a collection:

  1. See collection methods in docs, especially underscore methods

  2. You can add sorting methods to the collection by extending the Backbone Collection class, and then creating a new instance. example:

    var SortableCollection = Backbone.Collection.extend({
        sortThis: function() {
            // return 'this' sorted
        }
    });
    var collection = new SortableCollection();
    SortableCollection.sortThis();
    

Regarding fetching a collection, this answer may help

berri
  • 16
  • 1
  • Sorry, may be I didn't explain it well. I meant to actually sort the Items on the database via REST, not just for the sake of displaying sorted items with JS. – user2526586 May 27 '18 at 15:19