0

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!

1 Answer 1

1

You didn't bind the function but the result of the function, that is nothing.

Change

$(document).bind("load", NSVB.sub.init());

to

$(document).bind("load", NSVB.sub.init);

You have the same problem elsewhere (except of course if NSVB.puzzle.clicktest() returns a function):

    $("#click-test").bind("click",NSVB.puzzle.clicktest());
Sign up to request clarification or add additional context in comments.

3 Comments

I've tested your changes, but now nothing happens! In my example the function init() was called as expected, but the function clicktest() was called immediately and not when I click #click-test.
No, your function init() wasn't called as expected, it was called immediately, before the document loads. What I meant for the #click-test problem is that you must remove the parenthesis : $("#click-test").bind("click",NSVB.puzzle.clicktest);. Whether it will work will depend on the content of this function of course.
Ok, now I'm totally confused!! I've removed the parenthesis as you said! But, init() will not be called on load. But when i do this document.addEventListener("DOMContentLoaded",NSVB.sub.init,false); everything is fine!?!?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.