Currently I'm dealing with namespaces in javascript. As a first step I build a test page.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Namespace</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
var NSVB = NSVB || {};
NSVB.sub = {
init: function(){
alert("NSVB rocks");
$("#click-test").bind("click",NSVB.sub.clicktest());
},
clicktest: function(){
alert("clicked");
}
}
NSVB.sub.init = function(){
alert("NSVB rocks overwirtten");
$("#click-test").bind("click",NSVB.sub.clicktest());
}
$(document).bind("load", NSVB.sub.init());
</script>
</head>
<body>
<p id="click-test">click to test</p>
</body>
</html>
What I expect my code to do is:
- define the namespace with the function init() and clicktest()
- overwrite the function init()
- handle click event on #click-test when I click it
What my Code does:
- define the namespace with the function init() and clicktest()
- overwrite the function init()
- call clicktest()
- when I click nothing happens!!
I really don't get it! Hope someone could help.
Thanks in advance.
EDIT
After some testing I've have done the following:
Remove parenthesis
$("#click-test").bind("click",NSVB.sub.clicktest);
Replace
$(document).bind("load", NSVB.sub.init);
With (one of them, what you prefer to use)
document.addEventListener("DOMContentLoaded",NSVB.sub.init,false);
or
$(document).ready(function(e) {
NSVB.sub.init();
});
Everything works fine and as expected!