How to set javascript properties on a global listener, without duplicating code

39 views Asked by At

If I have multiple '.typeahead' input field on my page, and I want each of them to initialize typehead(), how can I make an exception for one specfic input element without duplicating my code? E.g.:

My fields:

<input type="text" class="typehead_selector" id="coworkers">
<input type="text" class="typehead_selector" id="jobs">
<input type="text" class="typehead_selector" id="search" data-action="search">

(the last one is the field I want to call typeahead() on, but with autoSelect set to false.

The script I had:

$(".typehead_selector").typeahead({
    autoSelect: true, // all typehead initilization have autoSelect

    updater: function (item) {
        // logic here
    }

        // ... more logic stripped here
});

My new script, which seem dirty to me?

$(".typehead_selector").each(function() { // added line

    var auto_select = true; // added line
    if($(this).data("action") == "search") { // added line
        auto_select = false; // now my searchfield will not have autoSelect enabled, hooray. but still, isn't this messy code?
    } // added line

    $(this).typeahead({ // now listening on $(this) instead of $(".typehead_selector")
        autoSelect: auto_select,

        updater: function (item) {
            // logic here
        }

        // ... more logic stripped here
    });
});

Greetings,

Michael

1

There are 1 answers

0
devconcept On BEST ANSWER

Use this

var options = {
    autoSelect: true, // all typehead initilization have autoSelect

    updater: function (item) {
        // logic here
    }

    // ... more logic stripped here
}

$(".typehead_selector:not(#search)").typeahead(options);
options.autoSelect = false;
$("#seach").typeahead(options);