I have an app with a page of items that have some sort options at the top. The items are using desandro's InfiniteScroll plugin.
When the page loads the infiniteScroll works fine. It grabs the URL from the paginator's next link and works great:
$('.car-grid').infiniteScroll({
path: '.paginator--cars .next_page a',
append: '.car',
scrollThreshold: 0
});
However, the problem comes when I click one of the sort options at the top. The click on the sort option is intercepted by my script, it first destroys the infinitescroll instance, then does an ajax call and gets returned a json file with two items. One is an html block of new cars and the second is the html of the updated paginator.
This is then fed into Handlebars.js and a template is used to update the page. I then reinitialise infinitescroll on the new set of cars.
The issue is that because the paginator was generated by the request on a .json URL, .json is added to all links in the paginator. this causes infiniteScroll to get the wrong type of result back and thus not work correctly.
Anyone have any suggestions on how I could get around this?
Here's the script:
$(document).on('change', '[type="radio"][name="sort"]', function() {
console.log('Destroying infiniteScroll');
$('.car-grid').infiniteScroll('destroy');
let selected = $(this).val();
let url = new URI();
url.removeQuery('sort');
url.addQuery('sort', selected);
url.removeSearch('page');
url.addQuery('page', 1);
url.suffix('json');
updateGrid(url);
});
function updateGrid(url) {
console.log(url);
$.ajax({
url: url,
type: 'GET',
success: function(data) {
let template = $('#car-grid-template').html();
let templateScript = Handlebars.compile(template);
let html = templateScript(data);
$('.thearea').html($(html));
$('.car-grid').infiniteScroll({
path: '.paginator .next_page a',
append: '.car',
scrollThreshold: 0
});
$('.car-grid').on( 'request.infiniteScroll', function( event, path ) {
console.log( 'Loading page: ' + path );
});
}
});
}
json.car_grid_html render partial: 'cars/car_grid.html.erb', locals: { cars: @cars }
json.paginator_html paginate(@cars, window: 1, outer_window: 2)
json.paginator_info_html page_entries_info(@cars)