S
S
svilkov872018-01-29 12:30:11
JavaScript
svilkov87, 2018-01-29 12:30:11

How to avoid code duplication?

Hello.

There is a piece of code:

$tabsTariff.each( function() {

        if ( $( this ).hasClass('b-tabs__item-title_state_current') ) {

            $linkPopup.attr( 'href', '#b-popup-classic-' + $( this ).attr('data-tab-name') ); 
        }

        $( this ).on( 'click', function() {

            $linkPopup.attr( 'href', '#b-popup-classic-' + $( this ).attr('data-tab-name') ); // дубль

        } );

    } );


What are the ways to avoid duplication?
$linkPopup.attr( 'href', '#b-popup-classic-' + $( this ).attr('data-tab-name') );
, even though I need to keep both the each loop and the click event?

Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
OKyJIucT, 2018-01-29
@svilkov87

Move the repetitive parts of the code into functions with parameters, and call them when necessary. for example, in such

function setHref(item, href) {
    item.attr('href', href); 
}

$tabsTariff.each( function() {

    var href = '#b-popup-classic-' + $( this ).attr('data-tab-name');

    if ( $( this ).hasClass('b-tabs__item-title_state_current') ) {

        setHref($linkPopup, href); 
    }

    $( this ).on( 'click', function() {

        setHref($linkPopup, href); // дубль

    } );

 } );

In this example, the savings are not significant, but you get the point.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question