Naresh
Naresh

Reputation: 25823

Why does RequireJS not load this dependency?

When executing the following 'main' module, I get a "TypeError: OrdersPage is not a constructor"

require(
    [
        'app/pages/orders/OrdersPage'
    ],
    function(OrdersPage) {
        'use strict';

        new OrdersPage();
    }
);

Turns out that when I am inside function(OrdersPage), "OrdersPage" is undefined. So the question is why is it undefined - in spite of defining OrdersPage as a dependency?

Here's the code for OrdersPage, which is actually being hit, but AFTER the above error is printed:

require(
    [
        'backbone'
    ],
    function() {
        'use strict';

        console.log('In OrdersPage');

        return Backbone.View.extend({

        });
    }
);

In summary, the console output is as follows:

TypeError: OrdersPage is not a constructor
In OrdersPage

This tells me that the OrdersPage module is being loaded after the 'main' module has been loaded and executed, which is too late!

Edit 1 A very simple project demonstrating this issue is available here.

Edit 2 I have already declared Backbone in my RequireJS configuration:

require.config({
    // Initialize the application with the main application file
    deps: ['main'],

    paths: {
        // jQuery
        jquery:                      'vendor/jquery-1.8.3',

        // Underscore
        underscore:                  'vendor/underscore-1.4.3',

        // Backbone
        backbone:                    'vendor/backbone-0.9.9',

        // Templating
        handlebars:                  'vendor/handlebars-1.0.rc.1'
    },

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

        handlebars: {
            exports: 'Handlebars'
        },

        underscore: {
            exports: '_'
        }
    }
});

require(
    [
        'app/pages/orders/main'
    ],
    function() {
        'use strict';
    }
);

Upvotes: 2

Views: 2214

Answers (1)

loganfsmyth
loganfsmyth

Reputation: 161657

You should be using define(), not require(). They are very similar, but require() does not do anything with the returned value and does not set up a module.

define(['backbone'], function() {
    'use strict';

    console.log('In OrdersPage');

    return Backbone.View.extend({

    });
});

Upvotes: 5

Related Questions