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

Deleting the main node in a JSON file containing multiple values

I am working with a JSON data stored in a variable. Here is the JSON Data: var employees = {"emp":{{"firstName":"John"},{"secondName":"John"}}}; My goal is to remove the emp node from the above JSON Data and have it as follows: {{"firstName":"John"},{" ...

Real-time filtering in personalized dropdown menu with search input

I have been attempting to create a custom list filter for input using a computed property. In one file, I am developing a widget, while in another file, I am implementing it. Below is the code snippet from the widget creation file: <template> ...

Why does adding to an array in the Vuex store replace all existing values with the last entry?

Utilizing vuex-typescript, here is an example of a single store module: import { getStoreAccessors } from "vuex-typescript"; import Vue from "vue"; import store from "../../store"; import { ActionContext } from "vuex"; class State { history: Array<o ...

Updating the variable in Angular 6 does not cause the view to refresh

I am facing an issue with my array variable that contains objects. Here is an example of how it looks: [{name: 'Name 1', price: '10$'}, {name: 'Name 2', price: '20$'}, ...] In my view, I have a list of products bei ...

What is the process for displaying the current bitcoin price on an HTML page using API integration?

I'm looking to develop an application that can display the current Bitcoin price by fetching data from the API at . I want to showcase this information within an h2 element. Any suggestions on how I could achieve this? Thank you in advance. const e ...

I encountered a permission denied error while attempting to execute the command npm install -g tsc

My main objective is to convert TypeScript code to JavaScript. However, when I attempted to install the TypeScript compiler globally using 'npm install -g tsc', I encountered the following error: npm ERR! Error: EACCES: permission denied, rename ...

Whenever I attempt to include additional drop-down lists, jQuery fails to function

My webpage features multiple drop down lists, with one populating based on the selection from another. Additionally, I have included a button at the bottom of the page. When this button is clicked, I need to add another column to the page. However, after ...

Accessing a JSON file from AWS S3 using Node.js

I was able to successfully read a JSON file stored in my S3 bucket, but I found myself having to perform various transformations that are somewhat unclear to me. When logging the data as it arrives, I am seeing an output of Buffer data s3.getObject(objPar ...

Vue.JS is throwing a TypeError: Unable to employ the 'in' operator to look for 'undefined' within the Laravel Object

How can I successfully pass an object from Laravel to Vue.js and utilize it in a v-for="option in this.options"? Although I am able to transfer the object from my Laravel blade to the Vue.js component and view it in the console, I encounter an error when a ...

Arranging hierarchical data in JavaScript

After populating the hierarchy data, it is structured as follows: Here is a screenshot: I am looking to sort this data. Currently, I have a flat data object for rendering purposes. For example, my rendering object looks like this: renderedobjects=[ {1,. ...

Is there a way to trigger a modal popup when hovering over a Bootstrap 5 card?

After coming across a handy template online, I decided to implement a modal pop-up feature when hovering over cards using Bootstrap 5. Here's what I have so far: class SavedEpisodes extends Component { $(function() { $('[data-toggle=&qu ...

Getting the result from a JavaScript request, whether it's synchronous or asynchronous

This code snippet involves a function that starts with a synchronous comparison test == 0. If the comparison is true, it returns one piece of content; however, if it's not, an asynchronous request is made. The goal here is for the latter part to retur ...

Dygraphs.js failing to display the second data point

My website features a graph for currency comparison using Dygraphs. Everything was working fine until I encountered this strange issue. https://i.stack.imgur.com/OGcCA.png The graph only displays the first and third values, consistently skipping the seco ...

The Coinbase Pay application fails to compile properly due to a missing Babel loader

Currently, I am working on integrating the coinbase pay sdk into my project. Although I have successfully created a button utilizing their provided examples, I am encountering an issue during the build process which seems to be internal to their SDK. Spec ...

What is the name of the scrolling header effect achieved in the following?

I've been seeing a lot of people using a unique header effect lately and I'm curious to learn more about how it's done. Can anyone explain the process behind achieving this effect, what it's called, and if there are any good tutorials a ...

Is there a way to efficiently remove deleted files from my Google Drive using a customized script?

After creating a function in Google Scripts to clear my trashed files, I ran it only to find that nothing happened. There were no logs generated either. function clearTrashed() { var files2 = DriveApp.getFiles(); while (files2.hasNext()) { var c ...

Adjust the text within the paragraph dynamically according to the option chosen in the drop-down menu using

I'm having trouble updating a paragraph in a letter based on the user's selection from a dropdown menu. I can't seem to figure it out. I don't know whether ng-show/hide or ng-options is the best approach for this. I feel completely los ...

Ways to correct inverted text in live syntax highlighting using javascript

My coding script has a highlighting feature for keywords, but unfortunately, it is causing some unwanted effects like reversing and mixing up the text. I am seeking assistance to fix this issue, whether it be by un-reversing the text, moving the cursor to ...

Searching for a MongoDB document using its unique identifier

Currently, I am working with Node.js and MongoDB where my database is hosted on MongoHQ (now compose.io). I have come to understand that document IDs are converted to hex strings, but I am struggling to retrieve a document using its ID. In my dataset, the ...

Ways to conceal ng repeat using ng if

My autocomplete feature is set up using ng-repeat to display suggestions and ng-click to change the textbox value. However, I am facing an issue where the suggestion does not disappear when the textbox value is already the same as the suggestion. How can I ...