I’m trying to learn to structure my code better, and have started using the pattern below after following a few tutorials.
I’ve had a fair amount of success building a number of common UI widgets this way, though I’ve hit my first wall, the .each() loops below do not seem to actually be looping through each item but are applying the desired action as if it was acting on all of the items in one iteration.
I read something about $.each and objects, though I’m not sure about $.each, or even whether it is teh direction I should be going.
jQuery(document).ready(function($) {
var tabs = {
trig : $('nav.tab-triggers'),
content : $('section.tabs-content'),
init : function() {
tabs.address([tabs.trig]);
tabs.address([tabs.content]);
},
address : function(item) {
//for every instance of the item
$(item).each(function() {
var i = 1;
$(this).addClass('tabs-' + i);
// for ever child element in this instance of the item
$(this).children().each(function() {
var count = 1;
if ( $(this).parent().is('nav') ) {
$(this).attr('href', '#tab-' + count);
} else {
$(this).attr('id', 'tab-' + count);
}
count++;
});
i++;
});
},
display : function () {
//show hide stuff here.
}
}
tabs.init();
});
So after much trial and error I’ve finally got it working.
basically, as I understand it, I’m trying to iterate over a nested objet and so the .each needs to be replaced with $.each method which works slightly differently.
Thats the new method – that works. Is there a better way to do this ?