0

I wanna structure my JS Code like the MVC Pattern.

Always when a site is loaded like index.php, a Controller Object will be created. And a function is called.

In the Controller.js File this function create a Model Object.

But I get an error which says that Model isn't a function.

File index.php

<script>
    var mController = new Controller();
    mController.load();
</script>

File Controller.js

 function Controller() 
 {
     console.log('IN CONTROLLER'); // OUTPUT: IN CONTROLLER 

     this.load = function()
     {
         var mModel = new Model(); // OUTPUT: Model is not a function
         mModel.load();
     }
 }

File Model.js

function Model() 
{
    this.load = function() { ... }
}

UPDATE: Error were the same name of variable and function.

2
  • I would call your variable something other than the function name. I would guess that this is a naming collision issue. Commented Sep 8, 2015 at 17:14
  • thx :) It really was a naming collision issue Commented Sep 8, 2015 at 17:17

1 Answer 1

3

You have some errors:

first: you have a var an a class/function that have the same name in:

var Controller = new Controller();

that's not good because one may obfuscate the other. Change that name. Also vars by convention start with small caps to differentiate them from functions.

then, this line:

this.load() = function()

should be:

this.load = function()

then if you're gettting the "Model is not a function" message is probably because you are not putting the js files in the right order. Model.js should came BEFORE Controller.js in the html. Please include the html part where these files are being loaded. I should be more or less like this:

<script type="text/javascript" src="Model.js"></script>
<script type="text/javascript" src="Controller.js"></script>

hope it helps.

Sign up to request clarification or add additional context in comments.

2 Comments

It was cause of the name. Ouu in the code the line is right, just wrote it false, thx for the input about the order of the files, I didn't know that
There are some frameworks and development styles that allow you to have better control about files that are loaded like require.js. Take a look at it: requirejs.org also learn about AMD and CommonJs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.