In my code, I have a series of page states that mimic the steps of a shopping cart checkout process. The first set of code sets up the ItemsCollection, ItemsView, and ItemsApp in Backbone.js.
var ItemsCollection = Backbone.Collection.extend({
model: ItemModel,
url "/items"
});
var ItemsView = Backbone.View.extend({
// Event listener to select item
});
var ItemsApp = Backbone.View.extend({
// Fetch items collection and render each ItemsView
});
After selecting an item, the next step is to display the sellers of that item. This requires setting up the SellersCollection, SellersView, and SellersApp:
var SellersCollection = Backbone.Collection.extend({
model: SellersModel,
url "/sellers"
});
var SellersView = Backbone.View.extend({
// Event listener to select seller
});
var SellersApp = Backbone.View.extend({
// Fetch sellers collection and render each SellersView
});
Given these two states, I am contemplating the best place to instantiate the Sellers Collection, fetch the Sellers, and render the view. My thought is to combine the SellersApp and ItemsApp into one controller that decides which subview to render and which collection to fetch.
My proposed approach involves instantiating both collections in the main app namespace and fetching them as needed, rather than instantiating each collection only when the corresponding state (url) is called.
To implement this, I plan to create a MainApp view with methods for handling items and sellers. Then, outside the view, I will instantiate the ItemsCollection and SellersCollection:
// Instantiate outside the view
var MainApp = Backbone.View.extend({
attributes: {
"page": "items"
},
items: function(){
// Fetch items collection and render view
},
sellers: function() {
// Fetch sellers
}
});
Items = new ItemsCollection;
Sellers = new SellersCollection;
Regarding changing states, I am debating whether to explicitly call the fetch method in the MainApp based on user actions or to use a listener within the MainApp view to detect selections automatically.
I am exploring alternatives to using router.navigate - trigger and relying on the router to handle view and collection instantiation, as I have heard this may not be considered best practice.