luxiconn
luxiconn

Reputation: 173

Having Issues Getting Files Loaded Correctly With Require.js

A little background information for the question

So I wrote an application last year for a client and about halfway through the project I realized that I would need to have a lot of asynchronous functionality so I started writing moving a lot of the site functionality over to javascript. I ran into a fairly major issue with my dev environment and ended up having a lot of my javascript inside my php files just to save time.

Before handing the project over to the client I moved all the javascript into seperate files only split up by the different areas of the site. So I ended up with an admin.js, checkout.js, common.js, etc.

The Actual Problem

The client now wants to add more functionality to the site and I want to go ahead and structure the javascript correctly into different files and separate the model code from the view code.

I'd like to use requirejs so I don't have a bunch of script calls in the footer of every page and to also handle dependencies better.

The specific problem I'm having is that it doesn't seem to be loading my files correctly.

My main.js file

require.config({
  paths: {
    'course'    : 'models/course',
    'login_view': 'views/login/login_view',
    'config'    : 'config',
    'views'     : 'views/views',
    'session'   : 'models/session'
  }
});

require(['login_view'], function(login_view){
  login_view.init();
});

My login_view.js file

define(function() {
  var login_view = {
    init: function(){
      console.log(this);
    });
  };
});

When I load the application on my dev server I get this error, Uncaught TypeError: Cannot call method 'init' of undefined

Any help would be appreciated.

Upvotes: 0

Views: 108

Answers (1)

Joseph
Joseph

Reputation: 119827

Because a module must expose an interface which requiring modules can operate on (variables names replaced to avoid confusion of naming):

//login_view.js
define(function() {
  var opBoard = {
    init: function(){
      console.log('I am initted!');
    });
  };

  //expose opBoard containing init
  return opBoard;
});

//so if i required in require or depended in another module
require(['login_view'],function(lv){
  //lv is the exposed opBoard from the `login_view` module
  lv.init();
});

Upvotes: 2

Related Questions