Reputation: 39018
So we have a messaging system, sometimes there are multiple messages and each message has a different count of common contacts between the sender and receiver.
When there are multiple accepted messages, currently I'm using each
to find all rows with the class of .outbox_accepted_row
and then use a function to grab a member id and make an API call to get some data I need to display in those rows.
For example, row 1 has 7 common contacts, row 2 has 17. However currently how my code is written, the last number 17
overrides all the rows.
How should this be re-written?
// This will find 2 rows on the page, grab the member id's and call
// getNameGameCounts twice:
$(".outbox_accepted_row").each( function( i, el ) {
var elem = $( el );
var member_id = elem.data('member-id');
getNameGameCounts(member_id);
});
function getNameGameCounts(member_id) {
// Here I make the api call with the id to get the counts I need:
WHOAT.networking.getToServerWithAjax(('/api/v1/name_game/play/'+member_id), null, function (response) {
// response comes back
if (response) {
// if the response has contacts
if (response.contacts !== null || undefined) {
// here is the problem
// every row will get overridden with the last count :(
$(".outbox_accepted_row .name_game p").each( function( i, el ) {
var elem = $(el);
elem.html(response.contacts.length);
elem.addClass('open_modal');
});
wireGetNameGame();
}
}
});
};
Upvotes: 0
Views: 47
Reputation: 6693
Don't re-select; you already have the element in hand earlier. Use that to get the element you actually want to update and then use that in the response callback. Have a fiddle or plunker for a demonstration?
Upvotes: 0
Reputation: 3665
I think instead of changing the dom in the 2nd callback
elem.html(response.contacts.length);
you should do this in your first loop
$(".outbox_accepted_row").each
getNameGameCounts should only return you the data, rather than do another dom action, it might experience with aync issue and return undefined, you will need to use like async.js.
And another thing, are you sure you want to loop the ajax call? seems like a bad design.
Upvotes: 1