Creating a structured model design in Javascript using Backbone framework

I am relatively new to JavaScript, so please bear with me as I ask this question.

Currently, for my project, I am using NodeJS for the server and Backbone for the client. The idea is that the client will send a request to the server, which will then respond by sending a list of files stored on the server. My goal is to simply display this list of files to the user and allow them to click on a file to load its content by sending another request to the server.

In the client-side code, my model and collection are defined as follows:

app.MyFile = Backbone.Model.extend({
    defaults: {
        modifiedDate: new Date(),
        path: '',
        content: '' // content of the file
    }
});

var MyFileList = Backbone.Collection.extend({
  model: app.MyFile,
  url: '/api/files'
});

// create global collection of files
app.MyFiles = new MyFileList();

app.AppView = Backbone.View.extend({
  initialize: function () {
    // fetch all files
    app.MyFileList.fetch();
  }
});

// app.js (point of entry)
$(function() {
  // Kick things off by creating the **App**.
  new app.AppView();
});

And here is part of the server-side code:

var application_root = __dirname,
    express = require("express"), 

...
app.get('/api/files', function(req, res) {
    ...
    // return file list
}

app.get('/api/files/:id', function(req, res) {
    ...
    // return file content?
}

Since it would be inefficient to load and send back all files from the directory at once, I decided to create the model on the server side and populate modifiedDate and path, leaving content as null. However, the challenge now is how to populate the content when a user clicks on a file. I am unsure about how to manually send an HTTP request from a Backbone View or controller. Are there any better approaches to tackle this issue? One solution that comes to mind is creating another model that only stores modifiedDate and path, but this seems verbose and repetitive to me.

Answer №1

Based on the information available on the client side, it seems like additional code may not be necessary.

app.MyFiles = new MyFileList();

app.MyFiles.fetch().done(function() {
   // The collection has been fetched, but each model's content is empty.
   // It is assumed that you will display them in a view or views at this point.
});

If one of these items is clicked, you can retrieve the content.

var model = app.MyFiles.get(id);
model.fetch().done(function() {
    // Now, the model's content attribute will be populated.
});

It is possible that no additional code beyond what has been shown is required. This is because a model's fetch URL is typically generated automatically by appending the model's ID to its collection's URL.

For example, if your server returns a JSON array from '/api/files':

[{id:1, path:'foo'}, {id:2, path:'bar'}]

Then from '/api/files/1':

{id:1, path:'foo', content:'whatever'}

Answer №2

Upon clicking the file, trigger backbone's fetch function on the model to populate it with data retrieved from the server.

It is crucial that the server returns a collection first, with models containing at least an ID. Additional fields will be populated post fetch execution. Additionally, make sure to customize the model URL if it deviates from the default format of collection/id.

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

What are the steps to kick off my React App once I've cloned it?

Currently grappling with deploying my app using Netlify, I encountered an issue after cloning the app onto my new computer. > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8afee5eee5e6e3f9fefcb8cabba4baa4ba">[email  ...

Passing a variable as a property to a nested child component in Vue.js

I am curious about how to efficiently pass variables to nested components. Within my setup, I have a total of 3 components: Main Secondary Tertiary All of these components share a common variable (referred to as sharedVar). If I want to avoid using Vue ...

Comparing the use of .on in a directive versus in a controller

When deciding between attaching a directive to an element or binding an event inside the controller, what is considered best practice? Directive <openread-more what-to-expand="teds-bets-readmore" /> myApp.directive('openreadMore', functi ...

Adding one day to a date using TypeScript

Could someone please explain how to increment a date variable by 1 day in TypeScript? I'm looking for the best way to add a day to a date field in TypeScript. ...

jQuery - delete a single word that is case-sensitive

Is there a way to eliminate a specific case-sensitive word from a fully loaded webpage? The word in question is "Posts" and it appears within a div called #pd_top_rated_holder that is generated by Javascript. The Javascript code is sourced externally, so ...

The output from the NodeJS storage module function

Attempting to implement Two-Factor Authentication in my initial NodeJS project, which serves as a learning tool for Node. While the function correctly retrieves values from data_url, when I assign it to a variable and return data_url, it returns 'und ...

Steps to implement a fixed toolbar in Chrome while ensuring optimal functionality for all other fixed elements

Currently in the process of developing a Chrome extension, I'm interested in implementing a 60px height toolbar that remains visible at the top of all pages. I've researched various tutorials and articles on using CSS translateX, but encountered ...

JestJS: Async testing isn't halted

I am facing two issues with my jest test: Is there a way to define the Content collection only once instead of repeating it inside the test? I encountered this error: Jest did not exit one second after the test run has completed. This usually indicates ...

Tips for saving/downloading generated QR codes in React Native

Using this code allows me to generate QR Codes, but I am struggling with saving the generated QR Code in PNG or JPEG format. I have tried a few examples without success and I am continuing to try different methods. import React, { Component } from 'r ...

Updating a d3.js force-directed graph may retain previous JSON data during the reloading process

Having a d3.js force-directed graph that pulls data from a JSON feed, I encounter an issue when clicking on a node. Although the updated JSON is correct, the displayed graph does not reflect this new data. It seems like the graph is retaining previous info ...

JavaScript encountered a server error when attempting to utilize emotion/styled

import Link from "next/link"; import Image from "next/image"; import { Text, useColorModeValue } from "@chakra-ui/react"; import { styled } from "@emotion/styled" const LogoBox = styled.span` font-weight: bold; font ...

What could be causing the jQuery slidedown to malfunction within my table?

My slider is not working when I include a table on my website. The slider works fine without a table, but I need to display members in a table format. Can anyone help me identify the issue with my code? The information needs to be displayed below the nam ...

Differences between count() and length() methods in Protractor

When it comes to determining the number of elements inside the ElementArrayFinder (which is the result of calling element.all()), you have two options according to the documentation: $$(".myclass").length, detailed here: This approach involves using ...

Exploring data visualization through object classification in Angular JS

I am facing a scenario where my API returns a single JSON Object if there is only one element in the response, and an array of objects if there are more than one elements. This poses a challenge as I need to handle both cases without changing the JSON stru ...

Incorporating a Link into a Radio Button component in Material-UI using react-router

Greetings! I have two radio buttons and would like to include a link. I attempted to achieve this in the following manner: <RadioButton value="/searchByArtistAndName" label="Artist and Name" style={styles.radioButton} contai ...

How can you leverage ReactJS to create dynamic elements on a webpage

Hey there! I'm currently working on building a dynamic form using HTML inputs with an array of objects called Forms. Each object specifies the type of input to render. So far, I've successfully rendered text areas, but I'm struggling with ho ...

Having trouble triggering a click event on Ant Design menu button using jest and enzyme

Troubleshooting the simulation of a click event on the Menu component using Antd v4.3.1 Component: import React from 'react' import PropTypes from 'prop-types' import { Menu } from 'antd' import { SMALL_ICONS, PATHS } fro ...

What is the best way to navigate through an HTML node tree, including all of its sub elements, when walking through

Do you know of a way to iterate through the entire hierarchy of HTML elements and check each one for attributes and more without using JavaScript? We currently have a JavaScript solution that iterates through each child element and all their descendants. ...

The error message in AuthenticatedLayout.jsx on line 43 indicates a problem with trying to access properties of an undefined object, specifically the 'name'

I am encountering this issue react-dom.development.js:26923 Uncaught TypeError: Cannot read properties of undefined (reading 'name') at AuthenticatedLayout (AuthenticatedLayout.jsx:39:55) AuthenticatedLayout.jsx import { useState } from "re ...

Visual elements failing to load in canvas due to fs/nodejs integration

I've been working with nodesjs and fs to set up a server that can render an HTML page. The HTML page includes a script written in JavaScript to create a canvas, load an image, and draw the image on the canvas. I've run into an issue where when I ...