Reputation: 879
I am trying to create namespaces in JavaScript as in the following script:
var hlAdmin = hlAdmin || {};
hlAdmin.editCompany = function (src) {
// function script
}
Then I call the function in HTML:
onclick="hlAdmin.editCompany(123)"
I get a reference error: Cannot find "editCompany".
Anyone know why?
Upvotes: 0
Views: 1073
Reputation: 879
I found the problem.
The browsers (at least Aurora and Chrome) are dropping the namespace in the onclick attribute. When you look at the browser html the namespace has just disappeared from the markup.
Upvotes: 0
Reputation: 14645
Based on your comments I assume the following:
The equivalent script (and scoping is like):
<html><head>
</script>
var hlAdmin = hlAdmin || {};
hlAdmin.editCompany = function (src) {
// error in this script
}
</script>
</head></body>
<button onclick="hlAdmin.editCompany(123)">Caption</button>
</body></html>
In this example hlAdmin
is indeed in the global scope (the root-scope of the host, called window
in browsers).
If (in this example) you get reference error: Cannot find "editCompany"
, then one should look at other error-messages in your (browser's) error-log, because when there is a fatal error in the function for hlAdmin.editCompany
, then that function will not be created (hence .editCompany
becomes a property that points to undefined
instead of a method that points to the function OR .editCompany
doesn't even exist (depending on engine/error)).
To investigate if you indeed have a scoping-problem you could test this by: window['hlAdmin'] || (window['hlAdmin']={});
(or some equivalent variant). If that made the code work, then it seems you have some scoping-problem.
Hope these steps help someone in the future.
Upvotes: 1
Reputation: 4755
It's generally considered bad form to mix inline javascript and non-inline. The preferred way to do this would be to keep all the javascript in one place using an event handler:
window.hlAdmin = window.hlAdmin || {};
window.hlAdmin.editCompany = function (src) {
// function script
}
document.getElementById('yourElementId').onclick = function() {
hlAdmin.editCompany(123);
};
To more specifically address the issue: One thing that could cause this issue is if the hlAdmin
object is not ending up in the global scope. You stated that this declaration is "at the top of the JavaScript file", but if it's in any kind of function (such as a function set to window.onload
, or the jQuery $(function() { ... });
) it would not end up in the global scope when declared as a var
. A variable declared with var
will only end up globally scoped if it's in the root scope, outside of any kind of function. If rather than using var hlAdmin
you instead use window.hlAdmin
, this will make sure that even if you're inside a document ready function or something similar, you're creating your hlAdmin
in the global context, which will fix the problem if it is in fact an issue of scope.
Upvotes: 0