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.