Creating a universal App Namespace using Require.js and Backbone

I'm new to working with Require.js and I've encountered a problem that I initially thought would be simple, but it's turning out to be quite challenging.

My goal is to create a global namespace for my Backbone application and load it as a module. Below is the code for my namespace (main.js):

define(
['jquery',
  'underscore',
  'backbone',
  'GlobalRouter'
],
function($, _, Backbone) {
var App= {
    Models: {},
    Views: {},
    Collections: {},
    Routers: {},
    init: function() {
        new App.Routers.GlobalRouter();
        Backbone.history.start();
    }
}
return App;

});

Additionally, here is the content of my config.js file:

require.config({
// your configuration key/values here
baseUrl: "js",
paths: {
    'jquery' : '//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min',
    'underscore': 'vendor/underscore-min',
    'backbone': 'vendor/backbone-min',
    'marionette': 'vendor/backbone.marionette',
    'main' : 'main'
},
shim: {
    'underscore': {
        exports: '_'
    },

    'backbone': {
        deps: ['underscore', 'jquery'],
        exports: 'Backbone'
    },

    'main' : {
        deps: ['underscore', 'jquery', 'backbone', 'GlobalRouter'],
        exports: 'TEWC'
    }

}
});

define([
'jquery',
   'underscore',
  'backbone',
  'main'
],
function($, _, Backbone, App, GlobalRouter) {
console.log(App)
alert('hit ')
  $(function() {
       App.init();
    });
 }

;)

For reference, included below is the structure of my router:

define([
'jquery',
'underscore',
'backbone',
'main'
],
function($, _, Backbone, TEWC) {

TEWC.Routers.GlobalRouter = Backbone.Router.extend({
    routes: {
        "" : "index",
        "documents/:id" : "edit",
        "login" : "login"
    },

    edit: function(id) {
        alert('edit')
    },

    index: function() {
        alert('index')
    },

    login: function() {
        alert('login')
    }
});

});

I was previously encountering an error stating 'app is undefined'. Now, after a few minutes, I'm receiving a load timeout error which reads:

Uncaught Error: Load timeout for modules: main

Despite this, the alert isn't triggered and it seems like main.js is not being loaded. However, I suspect the router is loading since there are no errors regarding TEWC being undefined - could it be loading without appearing in the Network tab?

This may be a basic inquiry, does anyone have any insights on how to resolve this issue?

Answer №1

The code snippet below does not include the definition for GlobalRouter, yet it is being passed to the define callback.

define([
'jquery',
   'underscore',
  'backbone',
  'main'
],
function($, _, Backbone, App, GlobalRouter) {
console.log(App)
alert('hit ')
  $(function() {
       App.init();
    });
 }

To fix this issue, make sure to add GlobalRouter to the define function parameters.

Additionally, if there is an error loading the main module, you can check the console to see what URL it is attempting to access. This could indicate a misconfiguration in the setup.

Answer №2

It seems like the issue lies in your config.js file. Instead of using define() after the require.config(), you should be using require().

To clarify, your current setup looks like this:

define([
'jquery',
   'underscore',
  'backbone',
  'main'
...

The use of define here should be replaced with require, as this is code that needs to be executed rather than defining a module.

Also, don't forget about the missing dependency for GlobalRouter as mentioned earlier.

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

How can scripts communicate with one another through passing arguments?

"scripts": { "dev": "npm run development", "development": "run-something", .... When invoking my script, I use the following command: npm run dev This is a convenient shortcut that executes the standard command npm-run-development. Is there ...

What is the process for implementing save-exact in bunfig.toml file?

Do bun repositories have a setting similar to .npmrc's save-exact configuration? I attempted to include save-exact = true in bunfig.toml but it did not have any effect. My bun version is 1.0.0. ...

How can I import an excel spreadsheet using Javascript, or alternatively, convert an excel file to a text document

I have been updating my file upload page to handle both text and excel files. However, when trying to read excel files with my current code, I am getting strange output. It seems that my function, which was originally designed for text files, needs modific ...

Adjust the path of an element as it decreases in size

Sorry for the weird title, but that's likely why I can't find the solution on my own. I'm experimenting with CSS animations and I want the form element to decrease in height from 100px -> 0, but I want it to collapse from the top to the ...

The persistent Expo in-app purchase sandbox pop-up continues to plague, hindering the completion of the test purchase

After creating my app using Expo and integrating Revenuecat for payments, I encountered an issue while testing it. Whenever I try to subscribe, the purchase popup keeps reappearing in Sandbox mode even after clicking 'Done'. Despite entering vali ...

Is it possible for an object to be null even when its type is object

There's an issue that I can't seem to replicate. Personally, I'm not experiencing any errors but bugsnag reports that some users are encountering them. Take a look at snippet line 6 for more information. let lang = this.$store.state.lang ...

How to iterate through two arrays using AngularJS ng-repeat

I have been attempting to create a specific layout by iterating through two arrays However, the output I am receiving from the ng-repeats does not match my desired view Below is the current code that I am working with: $scope.properties = ["First name", ...

I'm curious about the origin and purpose of req.user - where does it come from and

Recently, I've been delving into Nestjs and found myself a bit puzzled by the req.user. Where does this come from and do we have to manually request it? What exactly is req.user and what advantages does it offer? Must I assign payload to it manually? ...

Delete an element from an array after a specified timeout period

I'm currently working on a Vue component that is responsible for displaying notifications which should automatically disappear after a set time. My Alert component triggers an 'expired' event and then I handle this event in the parent compon ...

Show Zeroes in Front of Input Numbers

I am working with two input fields that represent hours and minutes separately. <input type="number" min="0" max="24" step="1" value="00" class="hours"> <input type="number" min="0" max="0.60" step="0.01" value="00" class="minutes"> This se ...

Hiding Properties in NodeJS with MongoDB

My quest is to fetch a user object from my mongodb database : router.get('/', async (req, res) => { var user = await User.findOne({ _id: '5fe30ba2d8f18b353ce6c7c2' }).select('+password +token'); // it's ok, I can r ...

Guide on restricting the character count and displaying the leftover characters using PHP with Ajax

I've been working on implementing a feature to display the remaining characters in a PHP AJAX call. I was successful using JavaScript, but I'm having trouble doing it with AJAX in PHP. Can someone provide assistance? <script type="text/javasc ...

Can you explain the distinction between postMessage() and dispatchEvent() in relation to the origin policy?

Here is some code that I wrote. I tried setting the MessageEvent's origin to *, but I'm still getting an error in the console saying "Blocked a frame with origin "AAAA" from accessing a frame with origin "BBBB". Protocols, domains, and ports must ...

Error messages from the Outlook Web add-in are presented as helpful information

I need assistance in showing error notifications. Here is my code: Office.context.mailbox.item.notificationMessages.addAsync("error", { type: "errorMessage", message: "The add-in encountered an issue while processing this message." }) The respons ...

How can you incorporate TypeScript's dictionary type within a Mongoose schema?

When using TypeScript, the dictionary type format is: { [key: string]: string; } However, when I try to define a custom schema in mongoose, it doesn't work as expected. const users = new Schema({ [key: string]: String, }); I also attempted t ...

Alter the Header/Navigation to switch colors depending on the section of the website currently being viewed

I'm currently revamping my personal portfolio website and had an idea for a cool feature. I want the header/navigation bar to change color based on which section of the webpage it's in (the site is one page only). My initial thought was to add o ...

Using Typescript/JSX to assign a class instance by reference

Looking to access an object's property by reference? See the code snippet below; class Point{ x:number; y:number; constructor(x,y) { this.x=x; this.y=y; } } const a = { first: new Point(8,9), second: new Point(10,12) }; let someBoo ...

I am attempting to incorporate an NPM package as a plugin in my Next.js application in order to prevent the occurrence of a "Module not found: Can't resolve 'child_process'" error

While I have developed nuxt apps in the past, I am new to next.js apps. In my current next.js project, I am encountering difficulties with implementing 'google-auth-library' within a component. Below is the code snippet for the troublesome compon ...

There seems to be a glitch with Angular's ngRoute functionality

There has been a common topic discussed in this community, but I have not come across anyone facing the exact issue I encountered. As I attempted to run my SPA locally instead of on a server, I realized I had to switch from Chrome/Explorer to Firefox. Th ...

Creating an array of objects by utilizing another array - the process explained

I am looking to create a new array by pushing objects after checking the values in an existing array. Here are the conditions: var ar=['aa','cc','po'] var arr =[{name:"po"},{name:'aa'},{name:'cc'}]; Desi ...