Mastering Backbone views and router functionality is essential for building scalable and efficient web

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.

Answer №1

When working with Backbone, especially Backbone Views, there isn't a clear-cut "right" way to do things. There's no set convention to follow. Many users of Backbone choose to only utilize the Models/Collections and skip using Views altogether.

In my view, unless a view for a collection is performing essential tasks, it might be best to avoid creating one. Instead, consider organizing your structure as follows: App > ModelCollection+ModelViewCollection.

For example:

ItemsApp (Backbone.View)
--ItemCollection (Backbone.Collection)
  --Item (Backbone.Model)
    -- SellerCollection (Backbone.Collection)
--ItemViewCollection (Array)
  --ItemView (Backbone.View)
    -- SellerViewCollection (Array)

In this setup, the ItemsApp would handle the creation and deletion of ItemViews as the ItemCollection undergoes changes (listening to events).

The responsibility of the ItemView lies in recognizing when a user selects it based on an event. It can then decide whether to populate the SellerCollection on its model upon selection. When deselected, it could clear that collection. The ItemView should also respond to changes in the SellerCollection by adding or removing views for each seller.

There doesn't seem to be an in-built method for storing a list of Backbone.Views, so creating your own array may be necessary. Remember, it's important to manually keep track of the views since a model shouldn't have a direct reference to its view.

Consider implementing a global event object to function as a messaging system. With Backbone.View utilizing Backbone.Events, you can declare your app object globally and listen to any related events. However, only use this approach when necessary; otherwise, it's recommended to listen to events directly without triggering them globally. For instance, your ItemView may feature a "Back" button that triggers a "back" event within itself, while the AppView listens to events on the active ItemView and manages DOM changes accordingly to deselect that item.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting JSON into Typescript class within an Angular application

As I work on my app using angular and typescript, everything is coming together smoothly except for one persistent issue. I have entity/model classes that I want to pass around in the app, with data sourced from JSON through $resource calls. Here's ...

The argument type does not match the parameter type partial<>

While attempting to validate my Ionic React form, I encountered an error when calling the validationSchema within the useForm method. The specific error message received is as follows: Argument of type '{ validationSchema: ......' is not assignab ...

What is the best way to utilize the features of component A within component B when they exist as separate entities

Component A has all the necessary functionalities, and I want to use it in Component B. The code for ComponentA.ts is extensive, but it's not written in a service. How can I utilize the logic from Component A without using a service, considering both ...

How can I store an access token received from the backend (in JSON format) in local storage and use it to log in?

My goal is to create a login interface using Plain Javascript. I have obtained a Token from the backend and now need assistance in utilizing this Token for the login process and storing it in LocalStorage. Although I have successfully made the API call, I ...

Implementing Next.js in a live production environment

I've been using next.js for some time now, but I'm still trying to wrap my head around how it operates in a production environment. As far as I understand it, when a request is made to the server, the server retrieves the requested page from the ...

What is the best way to inject child nodes into parent nodes without causing the view to shift to the location where the element is being

While I am rendering elements and appending them to a parent div, my screen keeps jumping to the bottom-most element as it loads instead of maintaining the current view. Ideally, it should start at the top of the screen and remain there without any sudden ...

What could be causing the CSS transition to fail when the menu button is clicked?

After clicking on the menu, a class 'active' is added to both the 'div' and 'section' elements. https://i.stack.imgur.com/jbamR.png The following javascript code accomplishes the above functionality: <script> const ...

Exploring a JavaScript file with the power of JavaScript and HTML

I have a .js file that contains the following data (excerpt for brevity) var albums= "tracks":[ {"title":"Dunnock","mp3":"Birdsong-Dunnock.mp3", "lyrics":"The Dunnock or hedge sparrow has a fast warbling song often delivered from t ...

`How can I enable the download attribute feature on Safari browser?`

Is there a workaround for saving files with a specified name in Safari? The following HTML code does not work properly in Safari, as it saves the file as 'unknown' without an extension name. <a href="data:application/csv;charset=utf-8,Col1%2C ...

The nth-child selector fails to function properly with a customized MUI component in CSS

I've created a styled component as shown below: const FormBox = styled(Box)(({ theme }) => ({ width: "47vw", height: "25vh", backgroundColor: theme.palette.grey[100], borderRadius: theme.shape.borderRadius, marginLeft: ...

Exploring SQL Components with JavaScript

Here is the code I am currently using: //This function handles all games and their attributes function handleGames(){ sql.query('SELECT id FROM games', function (err, rows){ if(err){ console.log(String(err).error.bgWhite) ...

I am having issues with the external CSS and JS files not functioning properly in my project

I'm currently working on a project that has the following file structure: However, I am facing issues with loading my CSS and JS files... <link rel="stylesheet" href="./css/main.css"> <script src="./js/main.js" ...

Errors in Compiling Dependencies for d3.js Using Typescript

Currently, I am in the process of developing a web application utilizing Node.js alongside Angular, Typescript, and d3.js, among other technologies. The application is functioning properly with library features working as expected. However, I am encounteri ...

Guide to launching my application by clicking on a file from a local device using React Native

Currently, I am working with React Native and Expo. I have a file with a unique extension (let's say: SomeFileName.xxx) which contains some text. My goal is to open this file from the device in such a way that it launches the application (either on An ...

Remove the ability to select from the dropped list item

Here is the HTML and Javascript code I used to enable drag and drop functionality for list items from one div to another: HTML: <div class="listArea"> <h4> Drag and Drop list in Green Area: </h4> <ul class="unstyle"> & ...

"Encountering difficulties while setting up an Angular project

I am currently working on setting up an Angular project from scratch. Here are the steps I have taken so far: First, I installed Node.js Then, I proceeded to install Angular CLI using the command: npm install -g @angular/cli@latest The versions of the ...

Methods for transforming a TypeScript class instance containing getter/setter properties into a JSON format for storage within a MySQL database

I am currently working on a TypeScript class that includes a getter and setter method: export class KitSection { uid: string; order: number; set layout(layout: KitLayout) { this._layout = new KitLayout(layout); } get layout( ...

Executing functions with iterations

Can anyone help me understand why my buttons always output 100 in the console log when clicked? Any ideas on how to resolve this issue? function SampleFunction(param){ console.log(param); } for (i = 0; i < 100; i++) { $("#btn-" + i).on('c ...

What is the best way to establish a maximum limit for a counter within an onclick event?

I'm struggling to figure out how to set a maximum limit for a counter in my onclick event. Can someone help me? What is the best way to add a max limit to the counter of an onclick event? Do I need to use an if statement? If yes, how should it be w ...

Currently dealing with a script that utilizes AJAX GET to incorporate JSON data into my table

Greetings and thank you for taking the time to read this! Within my HTML, I have implemented a form element that allows inputting data into 5 different fields. This data is then transmitted to a database using my unique API key. Once stored in the database ...