I am REALLY hoping this doesn't have a simple explanation, since that would mean lots and lots of lost hours (although that won't change the fact that they're lost anyway.) Some help or a kick in the right direction would be a deadline saver. Please.
I am trying to achieve the following;
1.) create a list of links that is populated by the JSON file (works)
2.) bind a click event on each li or a that passes a category object along to a builder function (think this works)
3.) user that object to do some cool stuff
However, there is some weird repetition going on once I reach my builder function.
Consider my JSON file called categories.json:
[
{
"category": [
{
"id": "1",
"title": "Title 1",
"values": [
{
"eg": [
{
"number": "12000000"
}
]
}
]
}
]
},
{
"category": [
{
"id": "2",
"title": "Title 2",
"values": [
{
"eg": [
{
"number": "37000000"
}
]
}
]
}
]
},
{
"category": [
{
"id": "3",
"title": "Title 3",
"values": [
{
"eg": [
{
"number": "37000000"
}
]
}
]
}
]
}
]
And then where I am definitely going wrong, my JS:
$(document).ready(function() {
//Get the necessary data from the JSON file
$.getJSON("categories.json", function(categories) {
$.each(categories, function(c, category) {
var link = new Nav(category.category);
});
});
Nav = function(groups){
$.each(groups, function(g, group) {
//console.log(group);
$('#categories').append('<li><a href="#">'+group.title+'</a></li>').data(group);
$('#categories li a').on('click', function(){
var builder = new Builder(group);
});
//$('#categories').append('<li><a href="#">'+this.title+'</a></li>');
//$('#categories').append(
// $("<li/>", { id: links.id, text: links.title}).data('navver', links)
//);
});
};
Builder = function(builder){
console.log(builder);
};
});
As you can see there are some other "tries" commented out. So when I click on the FIRST generated link, I get this output in console.log:
Object { id="1", title="Title 1", values=[1]}
Object { id="2", title="Title 2", values=[1]}
Object { id="3", title="Title 3", values=[1]}
Which is the entire array, and not just the first item. When I click on the second link:
Object { id="2", title="Title 2", values=[1]}
Object { id="3", title="Title 3", values=[1]}
And when I click on the third link:
Object { id="3", title="Title 3", values=[1]}
What I would like to happen, is that the correct object gets returned when I click on the corresponding link.
Are there any smart chaps out there with some time on their hands that would please help me out?