Search code examples
javascriptjqueryrefactoringjavascript-objectsdry

Javascript Refactoring, Following DRY method - How would you clone options passed into a plugin?


Since I'm trying to follow the DRY pattern, how would someone do something like this? (but the correct way)?

const lazyObj = {
  bind: 'event',
  effect: 'fadeIn',
  effectTime: 500,
  threshold: 0
}

$('.js-lazy, .js-lazy-homepage').lazy(lazyObj);

$('.js-other-lazy').lazy({
  ...lazyObj,
  beforeLoad: function() {
    $('.js-skeleton').hide();
  }
})

Essentially would want to rewrite this:

$('.js-lazy, .js-lazy-homepage').lazy({
  bind: 'event',
  effect: 'fadeIn',
  effectTime: 500,
  threshold: 0
});

$('.js-other-lazy').lazy({
  bind: 'event',
  effect: 'fadeIn',
  effectTime: 500,
  threshold: 0,
  beforeLoad: function() {
    $('.js-skeleton').hide();
  }
})

Since I'm using the same values:

{
  bind: 'event',
  effect: 'fadeIn',
  effectTime: 500,
  threshold: 0
}

Solution

  • You can extend and object into another. https://api.jquery.com/jQuery.extend

    var primary = {
      bind: 'event',
      effect: 'fadeIn',
      effectTime: 500,
      threshold: 0
    };
    
    var secondary = jQuery.extend(
      { beforeLoad: function() { $('.js-skeleton').hide(); } },
      primary
    );
    
    console.log(primary);
    console.log(secondary);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>