Anonymous Functions and HTML

Pardon my ignorance but I am trying to improve my JavaScript skills and treat it like a first class language. I have been reading about how to properly scope JavaScript so you keep it out of the global scope by using anonymous functions. I am all for that but I am not quite sure how it works with HTML. I have constructed a small example to explain my confusion. I have a function inside of an anonymous function to keep it out of the global scope.


(function {
    function doWork() {
        alert("Do work");
    }
})();

Now I want to call that function from inside my HTML page.

<a href="#" onclick="doWork()">Click Link</a>

Whenever I try to do that, obviously, it can’t find the function. How do I make the HTML aware of JavaScript functions that are inside the anonymous function? Is there some sort of best practice in these situations? Thanks for all your help in advance.

You need to put all the JavaScript inside the anonymous function - you can’t have part inside and part outside. Perhaps try like this with all the JavaScript inside the anon function.

(function {
    function doWork() {
        alert("Do work");
    }
    document.getElementById('work').onclick=doWork;
})();

and

<a href="#" id="work">Click Link</a>

For this version to work the javaScript would need to come after that HTML in order for it to be able to attach the onclick.

So with the code in the correct order (and a few errors fixed) it would be:


<a href="#" id="work">Click Link</a>


(function () {
    function doWork() {
        alert("Do work");
    }
    document.getElementById('work').onclick=doWork;
})();

and if you wanted to, you could even assign an anonymous function to the onclick event


(function () {
    document.getElementById('work').onclick = function () {
        alert("Do work");
    }
})();

If the link requires JavaScript to work, it should be created with JavaScript. Otherwise people like me get an annoying, non-functional link.

<div id="work"></div>
(function () {
    var a = document.createElement("a");
    a.href = "#";
    a.onclick = function () {
        alert("Do work");
        return false;
    };
    a.appendChild(document.createTextNode("Click Link"));
    document.getElementById("work").appendChild(a);
})();

Another idea is that if the link isn’t going to some other page, it should perhaps be a button instead.


(function () {
    var button = document.createElement("button");
    button.onclick = function () {
        alert("Do work");
    };
    button.appendChild(document.createTextNode("Click Me"));
    document.getElementById("work").appendChild(button);
})();

That will create a button similar to the following:


<button>Do Work</button>

Another Idea is to try and safely namespace your methods so that only One object pollutes the global space. A good namespace could be either your library’s unique name or better yet, a play on your domain name:


(function() {
/*
    check if it's already in the global namespace...
    There's a lot of things you could do if it is
    already there, like comparing versions etc...
    But I'll leave that one to figure out for yourself.
*/
    if ('undefined' == typeof window.ViperLib) {
        window.ViperLib = {
          doSomething: function(){
            alert('you clicked the link');
          }
        }
    }
})()
/*
  then, in your HTML you could add an event
  handler to the onclick that calls:
  ViperLib.doSomething();
  */

That’s a good idea. You could even make it more modular by having the code add on to the global namespace instead. That way you can add several different pieces without them needing to be defined at the same time.


(function () {
    if (!window.ViperLib) {
        window.ViperLib = {};
    }
    ViperLib.doSomething = function () {
        alert('you clicked the link');
    }
})();

indubitably!

Thank you all for your replies. I think I am beginning to understand OOP JavaScript a bit more now. I definitely like the idea of properly namsepacing my JavaScript. It makes me a lot more comfortable like a I am coding on the server.
In a semi-related question, I am very interested in learning more about OOP JavaScript concepts, like namespacing, anonymous functions, etc and I am looking for some good resources. Are there any good books/sites on how to write solid, robust, modern OOP JavaScript that you recommend. Thanks.

Basics of javascript:
This site and his book: www.quirksmode.org (PPK is a cross-browser god)

And then of course Douglas Crockford:
http://javascript.crockford.com/ (http://www.crockford.com/)

I dont believe much in buying a thousand books on this. I believe if it’s about the internet… then the best answer must be on the internet.

I know of one physical book specifically on “Object-Oriented JavaScript”. Its written by Stoyan Stefanov and published by Pakt Publishing and is called “Object-Oriented JavaScript”.