Katie
Katie

Reputation: 48208

How to call RequireJS functions in other files? How to separate RequireJS files?

Instead of having one giant js file that has a whole bunch of "defines", how do I call my various "define" functions from other files?

I've been copying these examples, but still cannot get it to work:

Here is what I have so far:

main.js

require.config({
    baseUrl: '',
    paths: {
       jquery: '../libraries/jquery-1.10.2.min',
       simControlView: '../javascripts/simControlView'
    }
});

require(['jquery','loadPage'], function( $,loadPage) 
{ 
        loadPage();
});

define('loadPage', ['jquery'], function($)
{
    var simControlView = require(['./simControlView']);
    return function()
    {
         simControlView.showSimControlView(); //having problem here

    };
});

simControlView.js

define(['jquery'], function ($) {
    return {
        showSimControlView: function () {
            console.log("Hi!!");
        }
    }
});

Here is the error that I'm getting:

Uncaught TypeError: Object function d(e,c,h){var g,k;f.enableBuildCallback&&(c&&H(c))&&(c.__requireJsBuild=!0);if("string"===typeof e){if(H(c))return v(A("requireargs", "Invalid require call"),h);if(a&&s(N,e))return Ne;if(j.get)return j.get(i,e,a,d);g=n(e,a,!1,!0);g=g.id;return!s(r,g)?v(A("notloaded",'Module name "'+g+'" has not been loaded yet for context: '+b+(a?"":". Use require([])"))):r[g]}K();i.nextTick(function(){K();k=q(n(null,a));k.skipMap=f.skipMap;k.init(e,c,h,{enabled:!0});C()});return d} has no method 'showSimControlView'

See anything I'm doing wrong? Any help is appreciated!

Upvotes: 2

Views: 3228

Answers (1)

Paul Grime
Paul Grime

Reputation: 15104

Try moving all the dependencies to the dependency list you pass to define().

Also, the ordering may be important. I.e. the define() of a module may need to come before the require() that requires it (talking about the 'loadPage' module).

Also, if your paths config calls a module 'simControlView', then it needs to be referred to as 'simControlView', and not as './simControlView'.

E.g.:

define('loadPage', ['jquery', 'simControlView'], function($, simControlView) {
    return function() {
         simControlView.showSimControlView();
    };
});

require(['jquery', 'loadPage'], function($, loadPage) {
    loadPage();
});

Upvotes: 3

Related Questions