I am using the following code to load two underscore.js templates. Once the first link is clicked, the skeleton template is loaded. The first trigger executes the find bind, which executes the loadBookmarks function correctly, but the ‘loaded’ trigger never fires and the loadFriendBookmarks never executes. Why is this? Is there another way to make this happen?
$('#bookmarks-link').click(function() {
$('#bookmarks-count').text("0");
var skeleton = modalTemplate();
$('#bookmarks').append(skeleton);
$('#bookmarks').trigger('skeleton');
});
$('#bookmarks').bind('skeleton', function() {
$('#bookmarks .thumbnails').loadBookmarks( getBookmarksUrl(1) );
// If I add an alert('hi') here, it works perfectly.
$('#bookmarks').trigger('loaded');
});
$('#bookmarks').bind('loaded', function() {
$('#bookmarks .thumbnails a').each(function() {
$(this).bind('click', function() {
$('#bookmarks .bookmarks-table tbody').empty();
$('#bookmarks .bookmarks-table tbody').loadFriendBookmarks(
getFriendBookmarksUrl($(this).attr('data-item'))
);
});
});
});
So interesting enough, the triggers do work correctly: If I stick an alert in between loadBookmarks and trigger, everything works fine. If I take it out, then it doesn’t. Any idea why?
Based on your description and common sense, it sounds like
loadBookmarks()loads data from a remote source, such as an ajax call. This means thattrigger('loaded')can fire beforeloadBookmarks()has received the data. You can add a callback argument toloadBookmarks()and trigger the event there:But this requires your
loadBookmarksto know to call this function after it receives the data and creates the needed HTML – I can’t demonstrate this without seeing the actual code you have inloadBookmarks.Additional suggestion: don’t bind handlers this way, use event delegation instead:
This means that all elements matching the selector ‘#bookmarks .thumbnails a’ will call this click handler, even if they were added to the document after you called
on. Meaning you can delegate these events even before callingloadBookmarks, removing the need for theloadedevent at all. Plus, this way you only have one copy of the handler function in memory, as opposed to yourbindwhich created a separate copy of the function for eachanode.