Reputation: 1743
Hi Im having problems with javascript! i have main.js and Model.js. Model.js is a javascript oop class in need to access its functions in main.js how do i do that? I keep getting an error that Model is not defined. Are there tools needed for this to work or something is wrong in the code?
Model.js
Model = {};
Model.init = function() {
alert("model");
}
Model.getList = function(){
var list;
$.ajax(
{
url:'???',
type: 'GET',
dataType: 'json',
success: function(data)
{
list=data;
}
error: function(data)
{
alert("error");
}
});
return list;
}
main.js
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var testins=new Model();
var list=Model.getList();
alert("result: "+testins);
}
I really could use some help.
so I tried MrCode approach and for experimental reasons put the code in one file because main.js still could not access the Model.js file.
main.js
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
alert("aaa"); //first
var testins=new Model();
var list=testins.getList();
alert("result: "+testins); // third
alert("list"+list); //fourth
}
function Model()
{
this.init = function()
{
alert("Model");
}
this.getList = function()
{
var list;
$.ajax(
{
url:'??',
type: 'GET',
dataType: 'json',
success: function(data)
{
list=data;
alert("success"+list); //fifth
},
error: function(data)
{
alert("error");
}
});
alert("success"+list); //second
return(list);
}
}
but following the alerts i see the that the $.ajax part is done last.
Upvotes: 0
Views: 230
Reputation: 382132
Do
function Model() { // this is the "constructor"
}
And replace
Model.init = function() {
by
Model.prototype.init = function() { // provide the function to all instances
(and the same for getList)
This will enable
new Model()
init
function to be inherited by the objects you create with new Model()
.Use it like this :
var testins=new Model(); // create an instance
var list=testins.getList(); // call the instance method
You may be interested by this MDN document about prototype and inheritance.
Upvotes: 2
Reputation: 64526
function Model()
{
// define public methods
this.init = function()
{
alert("Model");
}
this.getList = function()
{
var list;
$.ajax(
{
url:'???',
type: 'GET',
dataType: 'json',
success: function(data)
{
list=data;
}
error: function(data)
{
alert("error");
}
});
return list;
}
}
var testins = new Model(); // create an instance of Model()
var list = testins.getList(); // call its method
Upvotes: 0