lingz/alphabetical_paginate

Should avoid multiple bindings

Closed this issue · 0 comments

Every time alpha_paginate is used in the page it binds a new function to the click event: this means that if it is used as a header and a footer it will bind the same function twice, sending the same request two times at the server.

In practice, before binding the element with the handler it should check if the element is already bound.

Current

$(document).on("click", ".pagination#alpha a", function(e) {
        var url = location.href, 
        letter = $(this).data("letter");
        if (/letter/.test(url)) {
            url = url.replace(/letter=[^&]*/, "letter=" + letter);
        } 
        else {
            if (/\?/.test(url)) {
                url += "&letter=" + letter;
            } 
            else {
                url += "?letter=" + letter;
            }
        }
        $(".pagination").html(img);
        //$.load(url + " #pagination_table");
        $.get(url, function(result) {
            $(".pagination").html($(".pagination", result));
            $("#pagination_table").html($("#pagination_table", result));
        });
        history.pushState(null, document.title, url);
        e.preventDefault();
    });

Fixed

This should work:

var navbar = $(".pagination#alpha a");
// Pick the handler list: just a quick check for the jQuery version (see here: http://bugs.jquery.com/ticket/10589)
var handlers = navbar.data ? navbar.data('events').click : jQuery._data(navbar[0], 'events').click;

if (-1 !== $.inArray(onNavbarClick, handlers) {
    $(document).on("click", ".pagination#alpha a", onNavbarClick);
}

function onNavbarClick(e) {
        var url = location.href, 
        letter = $(this).data("letter");
        if (/letter/.test(url)) {
            url = url.replace(/letter=[^&]*/, "letter=" + letter);
        } 
        else {
            if (/\?/.test(url)) {
                url += "&letter=" + letter;
            } 
            else {
                url += "?letter=" + letter;
            }
        }
        $(".pagination").html(img);
        //$.load(url + " #pagination_table");
        $.get(url, function(result) {
            $(".pagination").html($(".pagination", result));
            $("#pagination_table").html($("#pagination_table", result));
        });
        history.pushState(null, document.title, url);
        e.preventDefault();
    });