Reputation: 3234
Hey I am new to javascript and I am trying to create a simple mvc app.
This is my model.js:
function Question(question,hint,answer){
this.question = question;
this.hint = hint;
this.answer = answer;
}
This is my view.js:
function view(modelList){
this.modelList = modelList;
}
view.prototype.show = function(){
var length = this.modelList.length;
for(var i=0;i<length;i++){
alert(this.modelList[i].question);
console.log(this.modelList[i].question);
}
};
This is my controller.js:
function controller(modelList){
this.view = new view(modelList);
}
controller.prototype.show = function(){
this.view.show();
};
This is my index.html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="app.js"></script>
<script src="controller.js"></script>
<script src="model.js"></script>
<script src="view.js"></script>
</head>
<body>
</body>
</html>
When I run index.html on my browser, I am getting a error like this:
jQuery.Deferred exception: model is not defined ReferenceError: model is not defined at HTMLDocument. (file:///D:/Javascript/MVC/app.js:3:23) at j (https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js:2:29948) at k (https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js:2:30262) undefined
and
> Uncaught ReferenceError: model is not defined
at HTMLDocument.<anonymous> (app.js:3)
at j (jquery.min.js:2)
at k (jquery.min.js:2)
Can anyone please tell me where I am wrong??
ThankYou
EDIT:
This is my app.js:
$(function(){
var model1 = new model("question","hint","answer");
var model2 = new model("question2","hint2","answer2");
var modelList = {model1,model2};
var controller = new controller(modelList);
controller.show();
});
Upvotes: 0
Views: 673
Reputation: 140032
Here's the fixed version: https://jsfiddle.net/weeuedub/1/
controller
class to Controller
.The problem was this line:
var controller = new controller(...);
Because you were using the variable name "controller", it overrides the "controller" function declared above.
As a convention, try naming your classes starting with an uppercase letter.
Update: https://jsfiddle.net/weeuedub/2/
You were assigning modelList
as { model1, model2 }
, which is not an array you can iterate through by getting the length
. It's an object that is identical to: { model1: model1, model2: model2 }
. This is ES6 syntax that is not widely supported by browsers yet, and I assume it was just a typo on your part. The fix was to change that to [ model1, model2 ]
to get an array.
Upvotes: 1
Reputation: 29614
Your model.js defines a Question function
You should either change it to
function model(question,hint,answer){}
or change the instantiation to Question
.
var model1 = new Question("question","hint","answer");
var model2 = new Question("question2","hint2","answer2");
Upvotes: 0