简体   繁体   中英

How to combine similar event handlers?

I have two sets of event handlers that are nearly identical. Is there a way to combine them to make the code more DRY?

this.E.name is simply a pointer/reference to a DOM element.

Note that my IDs are different not the event types as in the possible duplicate which does not apply.

    /*set 1
    */
    $(this.E.main).on("click", function () {
        Page.flip('main');
    });
    $(this.E.feed).on("click", function () {
        Page.flip('feed');
    });
    $(this.E.so_button).on("click", function () {
        Backbone.trigger('user_sign_out');
        Pane.flip();
        Page.flip();
        Storage.clear();
    });

    /* set 2
    */
    $(this.E.main_nav).on("click", function () {
        Page.flip('main');
    });
    $(this.E.feed_nav).on("click", function () {
        Page.flip('feed');
    });
    $(this.E.so_button_nav).on("click", function () {
        Backbone.trigger('user_sign_out');
        Pane.flip();
        Page.flip();
        Storage.clear();
    });

You could be more tricky, and just iterate over the object

var valid = ['main', 'feed', 'so_button']; // in case there are other props in object
$.each(this.E, function(key, value) {

    if ( valid.indexOf(key) !== -1 || valid.indexOf(key + '_nav') !== -1 ) {

        $(this.E[key]).on('click', function() {
            if ( key.indexOf('so_button') !== -1 ) {
                Backbone.trigger('user_sign_out');
                Pane.flip();
                Page.flip();
                Storage.clear();
            } else {
                Page.flip(key)
            }
        });

    }
});

You can use comma , separator and square brackets [] to combine multiple selectors and use $(this) to refer to the current object clicked :

$([this.E.main, this.E.feed, this.E.main_nav, this.E.feed_nav]).on("click", function () {
    Page.flip($(this).attr('name'));
});

$([this.E.so_button, this.E.so_button_nav]).on("click", function () {
    Backbone.trigger('user_sign_out');
    Pane.flip();
    Page.flip();
    Storage.clear();
});

Hope this helps.

Your could make a utility javascript function/object that has a method for each one of your routines inside the events. The one liners would still be one liners and the 4 liners would become one liners. You aren't reducing the amount of code greatly but maintenance will be much better and future maintainability will be much better, especially when the more logic is added to the one liners.

try this

var mainId = "#" + this.E.main.id;
var mainNavId = "#" + this.E.main_nav.id;

$(mainId + "," + mainNavId ).on("click", function () {
    Page.flip('main');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM