DEV Community

StormyTalent
StormyTalent

Posted on

50+ hints JS(ES6+) developer must know (10th part)

My thanks to everybody who follows to this tenth, the last blog of JS hint.
Today we are going to see some useful cases of Accessors, Events, and JQuery.
1. Accessors

Do not use JavaScript getters/setters as they cause unexpected side effects and are harder to test, maintain, and reason about. Instead, if you do make accessor functions, use getVal() and setVal('hello').

// bad
class Dragon {
  get age() {
    // ...
  }

  set age(value) {
    // ...
  }
}

// good
class Dragon {
  getAge() {
    // ...
  }

  setAge(value) {
    // ...
  }
}
Enter fullscreen mode Exit fullscreen mode

If the property/method is a boolean, use isVal() or hasVal().

// bad
if (!dragon.age()) {
  return false;
}

// good
if (!dragon.hasAge()) {
  return false;
}
Enter fullscreen mode Exit fullscreen mode

It’s okay to create get() and set() functions, but be consistent.

class Jedi {
  constructor(options = {}) {
    const lightsaber = options.lightsaber || 'blue';
    this.set('lightsaber', lightsaber);
  }

  set(key, val) {
    this[key] = val;
  }

  get(key) {
    return this[key];
  }
}
Enter fullscreen mode Exit fullscreen mode

2. Events
When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass an object literal (also known as a "hash") instead of a raw value. This allows a subsequent contributor to add more data to the event payload without finding and updating every handler for the event. For example, instead of:

// bad
$(this).trigger('listingUpdated', listing.id);

// ...

$(this).on('listingUpdated', (e, listingID) => {
  // do something with listingID
});
Enter fullscreen mode Exit fullscreen mode
// good
$(this).trigger('listingUpdated', { listingID: listing.id });

// ...

$(this).on('listingUpdated', (e, data) => {
  // do something with data.listingID
});
Enter fullscreen mode Exit fullscreen mode

3. jQuery

// bad
const sidebar = $('.sidebar');

// good
const $sidebar = $('.sidebar');

// good
const $sidebarBtn = $('.sidebar-btn');
Enter fullscreen mode Exit fullscreen mode
// bad
function setSidebar() {
  $('.sidebar').hide();

  // ...

  $('.sidebar').css({
    'background-color': 'pink',
  });
}

// good
function setSidebar() {
  const $sidebar = $('.sidebar');
  $sidebar.hide();

  // ...

  $sidebar.css({
    'background-color': 'pink',
  });
}
Enter fullscreen mode Exit fullscreen mode

For DOM queries use Cascading $('.sidebar ul') or parent > child $('.sidebar > ul'). jsPerf

Use find with scoped jQuery object queries.

// bad
$('ul', '.sidebar').hide();

// bad
$('.sidebar').find('ul').hide();

// good
$('.sidebar ul').hide();

// good
$('.sidebar > ul').hide();

// good
$sidebar.find('ul').hide();
Enter fullscreen mode Exit fullscreen mode

Thanks for your time.
Best regards.

Top comments (0)