由于我尝试遵循DRY模式,有人会怎么做这样的事情? (但正确的方法)?
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();
}
})
基本上是要重写此:
$('.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();
}
})
因为我使用的是相同的值:
{
bind: 'event',
effect: 'fadeIn',
effectTime: 500,
threshold: 0
}
您可以扩展并反对另一个。 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>