Reputation: 739
In the 'simplified' JavaScript code below there is a problem with the function message_category_ref()
, which creates a link for some elements. When clicking on the created link the console shows the error:
Uncaught ReferenceError - showTopics is not defined.
When I include an alert()
function in the return statement instead of showTopics (as shown below), alert()
is called. Not sure why showTopics()
is not recognised and how to solve this?
Simplified code:
userapp = function(){
var showTopics = function(catid){
}//showTopics()
var showMessageCategories = function(){
showList4('Berichten','general-com','html','MessageCategoryTable',
['Categories','Subjects','Messages','Last message']);
addRow('MessageCategoryTable',['Privat message']);
for(var i=0,i_max=message_categories.length;i<i_max;i++){
addRow('MessageCategoryTable',[message_category_ref(message_categories[i]['catname'],message_categories[i]['catid'])]);
addRow('MessageCategoryTable',[message_categories[i]['catdescription']]);
}//for
//message_categories[0]
}//showMessageCategories
var message_category_ref = function(catname,catid){
//this one does not work
return '<a id="myLink'+catid+'" href="#" onclick="showTopics(\'' + catid + '\');">'+catname+'</a>';
//this one works
//return '<a id="myLink'+catid+'" href="#" onclick="alert(\'' + catid + '\');">'+catname+'</a>';
}//var message_category_ref
return{showMessageCategories:showMessageCategories}
}(); //userapp
$(document).ready(function(){
userapp.showMessageCategories();
}); //$(document).ready
Upvotes: 1
Views: 102
Reputation: 782166
The function name is local to the anonymous function you use to initialize userapp
, so it can't be accessed from an onclick
attribute -- these expressions are evaluated in the global scope.
Change the return
line to:
return{showMessageCategories:showMessageCategories,
showTopics: showTopics};
Then you can do:
onclick="userapp.showTopic(...
Upvotes: 4
Reputation: 12508
Your function is not global. It is located within a closure. You need to add it to your return object to allow it to be accessed outside userapp
:
return {
showMessageCategories: showMessageCategories,
showTopics: showTopics // Add this to your return Object
};
Also change your onclick
to reference it like so:
onclick="userapp.showTopics(\'' ... )"
Upvotes: 2