I’ve managed to avoid using namespace in most of my javascript dev to date, but I’m beginning to see the light through reading helpful articles like this one
I’m following Maeagers technique found here to create my namespace as shown below –
var newAndImproved = {
//div to put loaded content into
targetDiv: "",
//loads the initial content based on an anchor tag having a class named 'chosen'
loadInitialPage: function() {
var chosenLink = $("#subnavigation a.chosen");
newAndImproved.loadPartial(chosenLink);
},
loadPartial: function(clickedLink) {
var theUrlToLoad = $(clickedLink).attr("href");
$(newAndImproved.targetDiv).load(theUrlToLoad, function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$(targetDiv).html(msg);
}
});
},
removeClassFromSubNav: function() {
$("#subnavigation a").removeClass('chosen');
},
addChosenClassToNav: function(chosenLink) {
$(chosenLink).addClass('chosen');
},
bindMethodsToNavigation: function() {
$("#subnavigation a").bind('click', function(event) {
var chosenLink = event.target;
newAndImproved.removeClassFromSubNav();
newAndImproved.loadPartial(chosenLink);
newAndImproved.addChosenClassToNav(chosenLink);
return false;
});
}
};
I’ve called that namespace like this –
$(document).ready(function() {
newAndImproved.targetDiv = $("#subcontent");
newAndImproved.loadInitialPage();
newAndImproved.bindMethodsToNavigation();
});
I’m sure you’ve noticed that I’m referencing the namespace within itself rather than just using ‘this’. I assume this is incorrect. But when I use ‘this’ the binding part will not work.
Strangely, the loadInitialPage method will work when using ‘this’.
Any idea what I’m doing wrong?
Thanks in advance.
You need to use the
thattrick.thisgets re-assigned inside new scopes, including the anonymous function you are binding.Consider this code:
If you run this, it will behave nicely, and the references to
this.xxxall succeed as you would like. However, if you add a func3 like this:…it will not work as you might imagine. Because the anonymous function is defined in no explicitly-specified scope, the
thiswithin it refers to the top level object,window. And there is nofunc1as a child of window (no top level object namedfunc1).For the same reason, the
thiswithin your anon function that you use in the call tobind()will fail. In that case you can refer to the “namespace” object directly, or you can use a closure (some people call it “thethattrick”):The
thiswithin the scope ofbindMethodsToNavigationrefers tonewAndImproved. Thethiswithin the anonymous function will refer towindow. Using a closure allows you to refer to the thing you want. (editorial comment: I personally find the namethatto be cute and entirely unhelpful. I like to use abbreviated names, in your case maybe something likenaito refer tonewAndImproved)Incidentally, you could also do this:
…and if they are both members of the
newAndImprovedobject, then thethiswithinclickHandlerwill be resolved to thenewAndImprovedobject. The key here is thatclickHandleris not an anonymous, top-level function; it belongs tonewAndImprovedand whenthisis used within it, it resolves appropriately. Even more, you can just drop the use ofthiswithinclickHandler; it is not incorrect, but it is unnecessary. Some people like to add it for emphasis to those who might read the code later.EDIT
One more note on this – on the decision whether to use anonymous functions or named functions as event handlers… Anon functions are so convenient and easy, and everybody uses them. What I find is that in Firebug or the IE Javascript Debugger, when I look at a stack trace I get a loooong list of anon functions, and it’s difficult to figure out just what the chain of functions is. Especially with AJAX and async handlers being fired in response to UI events, and so on. To provide some additional visibility at debug time, I sometimes use named functions (put into namespaces), and the callstack will show a few named fns along interspersed with a few anon fns. This sometimes helps.
Just a small thing, though.