简体   繁体   中英

avoiding code duplication when assigning events

What is a good way to assign the same event triggered behavior to multiple of elements are a time

currently I just duplicate the code like this, but this is obviously not optimal

  $('.recipient #shipment_recipient_attributes_country_code').changeOrDelayedKey(function(e) {
    cargoflux.resetCarrierProductPriceFields();
    cargoflux.getAvailableCarrierProducts();
  }, 1000, 'keyup');

  $('#shipment_recipient_attributes_zip_code').changeOrDelayedKey(function(e) {
    cargoflux.resetCarrierProductPriceFields();
    cargoflux.getAvailableCarrierProducts();
    console.log('recp zip code')
  }, 2000, 'keyup');

  $('.sender #shipment_sender_attributes_country_code').changeOrDelayedKey(function(e) {
    cargoflux.resetCarrierProductPriceFields();
    cargoflux.getAvailableCarrierProducts();
  }, 1000, 'keyup');

  $('#shipment_sender_attributes_zip_code').changeOrDelayedKey(function(e) {
    cargoflux.resetCarrierProductPriceFields();
    cargoflux.getAvailableCarrierProducts();
  }, 2000, 'keyup');

Any suggestions?

You can add a class for all the elements, and add a data-delay attribute for the delay, and then apply the events to each element:

The markup:

<input class="someClass" id="some_id" data-delay="2000" ... />

The jQuery:

$(".someClass").each(function() {
    var $this = $(this);
    $this.changeOrDelayedKey(function(e) {
      cargoflux.resetCarrierProductPriceFields();
      cargoflux.getAvailableCarrierProducts();
    }, $this.data('delay'), 'keyup');
});

If you can change the HTML add a common class to each element in question, and as you have different data requirements (the timing varies) you can iterate over them and use data- attributes to hold to delay:

  $('.someclass').each(function(){
     $(this).changeOrDelayedKey(function(e) {
        cargoflux.resetCarrierProductPriceFields();
        cargoflux.getAvailableCarrierProducts();
  }, $(this).data('delay'), 'keyup');

And the elements will have data-delay="1000" or data-delay="2000" added (as well as the class you chose).

An alternative, if you have groups of fixed timings, is to apply different classes to the different time requirements and share a function:

eg

  function reset() {
        cargoflux.resetCarrierProductPriceFields();
        cargoflux.getAvailableCarrierProducts();
  }

  $('.someclass1000').changeOrDelayedKey(reset, 1000, 'keyup');
  $('.someclass2000').changeOrDelayedKey(reset, 2000, 'keyup');

You then just add class="someclass1000" or class="someclass2000" to get the desired effect.

Note: As you have id searches, and IDs must be unique on the page, the preceding .recipient has no effect on the search query (other than to slow down the search).

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