Efficiently managing modules with requirejs and Backbone.Marionette

After organizing the file structure of my web app, utilizing RequireJs and Backbone.Marionette, it now looks like this:

|- main.js
|- app.js
    |- /subapp1
        |- subapp1.js
        |- subapp1.router.js
    |- /subapp2
        |- subapp2.js
        |- subapp2.router.js
    |- /collections
    |- /views

To load the modules, I have incorporated requireJs.
Below is my code where each module has some associated questions.


// main.js
define([
    'app',
    'subapp1/subapp1.router',
    'subapp2/subapp2.router'
], function (app) {
    "use strict";
    app.start();
});

Questions:
1) Is it appropriate to asynchronously load the app and subapps even if subapps rely on the app?
2) Should the router which requires the app be loaded for the subApps?


// app.js
/*global define*/
define([
    'backbone',
    'marionette',
    'models/user'
], function (Backbone, Marionette, UserModel) {
    "use strict";

    var App = new Marionette.Application();

    App.addRegions({
        header: '#header',
        sidebar: '#sidebar',
        mainColumn: '#main-column',
        rightColumn: '#right-column'
    });

    App.on("initialize:before", function () {
        this.userModel = new UserModel();
        this.userModel.fetch();
    });

    App.on("initialize:after", function () {
        Backbone.history.start();
    });

    return App;
});

Questions:
3) Since the subApps may need some models, I decided to load them in app.js. Is this the correct approach?


// subapp1/subapp1.js
/*global define*/
define([
    'app',
    'subapp1/views/sidebarView',
    'subapp1/views/headerView'
], function (app, SidebarView, HeaderView) {
    "use strict";

    app.addInitializer(function(){
        app.header.show(new HeaderView({userModel: app.userModel}));
        app.sidebar.show(new SidebarView({userModel: app.userModel}));
    });

});

Question:
4) Regarding this module, I am uncertain about the app.addInitializer. I am unsure whether the app.userModel will be fetched when I execute app.header.show. Would that work correctly?


// subapp1/subapp1.router.js
/*global define*/
define([
    'marionette',
    'tasks/app'
], function (Marionette, app) {
    "use strict";
    var Router = Marionette.AppRouter.extend({

        appRoutes: {
            'tasks': 'tasks',
            'tasks/:id': 'taskDetail',
            '*defaults': 'tasks'
        }

    });

    return new Router({
        controller: app
    });
});

Question:
5) Is it acceptable to load the subapp1/subapp1.router from main.js rather than subapp1/subapp1?

Answer №1

1) Is it advisable to asynchronously load the main app and subapps even if subapps depend on the main app?

It is recommended to asynchronously load your app and any sub-apps. If a sub-app requires the main app, it should be listed as a dependency. RequireJS will handle resolving dependencies for you.

The only thing to be cautious of are circular dependencies, but they can usually be resolved easily.

2) Should the router for subApps be loaded in conjunction with the app?

Including the routers for your sub-apps in your main.js file is a good practice.

3) I have included loading models for subApps in app.js. Is this the correct approach?

A module should declare all modules it depends on. Therefore, if both app.js and subapp1/subapp1.js require models/user.js, both should list it as a dependency.

This method ensures that dependencies are managed properly and makes code clearer for future reference.

4) I am unsure about using app.addInitializer in this module.

I am uncertain whether app.userModel will be fetched when executing app.header.show. Is this behavior acceptable?

Data fetching should be triggered manually. Showing a view in a Region does not automatically fetch data for the view's Model or Collection.

You can make your view listen to events on the model or collection and re-render accordingly once new data is fetched successfully.

5) Can the subapp1/subapp1.router be loaded from main.js instead of subapp1/subapp1?

As mentioned earlier, loading routers in main.js is a good practice. This allows for lazy-loading of sub-apps only when needed.

Activating a sub-app's routes triggers its core module and dependencies to be loaded, making loading efficient and modular.

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

Issue "RangeError: minimumFractionDigits value is invalid" when using ChartJS in a Next.js application

I'm currently working on developing an application utilizing react-chartjs-2.js. The functionality is smooth in my local environment, but when moved to production, I encounter the following error: Application error: a client-side exception has occurre ...

Switch button for updating text, icon, and displaying search bar

Having trouble with a header and navigation bar setup. The goal is to have a search button that toggles between "Search" and "Close Search" when clicked, while also opening the search bar below the navigation. I've experimented with different methods ...

What is the process for getting the input value when a key is released?

My goal is to capture the actual value or text from an input field and store it in a variable. However, when I use the console to check the output, it shows me a number indicator that increments each time I type something. <input id="usp-custom-3" ty ...

Trouble with Background Image Display in Internet Explorer 8

I have been attempting to set a background image for the . element, but it is not displaying correctly. The image shows up in Firefox and Chrome, but not in Internet Explorer. I have included a link to my website and relevant CSS code below. Can anyone pro ...

Is it possible to modify the CSS styles for a specific portion of an input value?

Currently, I am in the process of developing a form using React.js where a specific input must match the label written above it. Here is an example: https://i.stack.imgur.com/S2wOV.png If there happens to be a typo, the text should turn red like this: h ...

Tips for retrieving nested data objects from a JSON API on the web

Below is the provided API link - I attempted to utilize this jQuery script in order to collect data for each state individually for my project. However, I am facing difficulties accessing the information with the code provided below. $.getJSON('http ...

Obtain the title of the text generated by clicking the button using a script function

I am working on a piece of code that generates a text box within a button's onclick function. My goal is to retrieve the name value of each text box using PHP. <script language="javascript"> var i = 1; function changeIt() ...

Tips for getting JavaScript to identify a context_dict object from views.py in Django

Recently, I inherited a Django project from a former colleague and now I need to make some changes to the code in order to add a new line to a Google Viz line chart. As the line chart already exists, my approach is to closely follow the logic used by my p ...

Sending a Variable and List to a Controller using Ajax

I am having an issue with passing data from a Text Box and a Select Options Multiple using knockout selectedOptions in a viewModel to my Controller via ajax. I am unable to receive the MetricsChosenModel information. var MetricsChosenModel= wi ...

Showing no background color until the user lifts their finger

I am currently in the process of developing a website. The navigation on the website starts off as transparent (background: transparent) when opened, but as soon as you start scrolling, it should transition to a colorful state with shades like grey, midnig ...

Retrieve an image located outside of a container

I have multiple SVGs inside separate div elements. <div id="divA"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <rect x="10" y="10" height="130" width="500" style="fill: #000000"/> ...

Storing the background color in a JavaScript variable

I've been experimenting with creating a fade in and out effect for a background image on a website. I've also been attempting to capture the background color of a div and store it in a variable. Here's what I have tried: elem = document.ge ...

What is the best way to incorporate a transition on transform using Styled-components?

I attempted to add a transition on the transform property, but unfortunately, it did not produce any visible changes. I tested other properties such as: background-color, color... and they worked perfectly fine. live code: source code: // styled-compo ...

Sharing a state object with another React file can be accomplished by using props or context to

My first React file makes an API call to retrieve data and save it in the state as Data. import React, { Component } from "react"; import axios from "axios"; import Layout from "./Layout"; class Db extends Component { constructor() { super(); th ...

Issue with using Sinon FakeServer with Mocha

I'm currently in the process of setting up a test for an API call. In my attempt to create a fake server within the before method, I have encountered issues with testing the basic implementation using $.ajax compared to my actual api call. Strangely, ...

Sketch the borders of the element (animated)

Seeking a way to create a button with an animated border that looks like it is being drawn. Current progress involves some code, but it's not working smoothly with border-radius set. (keep an eye on the corners) https://codepen.io/anon/pen/MbWagQ & ...

Certain conditions in JavaScript are not executed by Internet Explorer

I am currently working on a Html file that involves XSLT. I have integrated some JavaScript code for filtering specific rows within tables. However, I have encountered an issue where certain if-cases in my JavaScript are not executing as expected when usin ...

"Implementing a sorting feature in a product filtering system with JavaScript/Vue, allowing

I have a dataset structured like this: > Price : ["800000","989000","780000","349000"] If the user selects 'sort by lowest price', I want the data to be arranged from the lowest price to the highest price as follows: > Price : ["349000" ...

When trying to access the "form" property of a form ElementRef, TypeScript throws an error

I've encountered an issue with accessing the validity of a form in my template: <form #heroForm="ngForm" (ngSubmit)="onSubmit()"> After adding it as a ViewChild in the controller: @ViewChild('heroForm') heroForm: ElementRef; Trying ...

The JSON file gets emptied every time I refresh the page repeatedly

I am encountering an issue where my JSON file gets cleared if I restart the page quickly after using the fs module to read/write it. The JSON data is read at the beginning of the page like this: let preferencesJSON; try { preferencesJSON = fs.readFile ...