JavaScript to capture a class value

What a great smorgasbord of solutions. I’m savoring each one. Thanks very much @Paul_Wilkins, @m3g4p0p and @James_Hibbard.

I did think it would be better to target the one element, but wasn’t sure what to do next. Thanks for covering that, Paul.

1 Like

Oh good call! Now what you might do then is not to hard-check against the nodeName property, but to extract that delegation functionality using matches() for reusability. Like, can of worms… :-D

function connectHandler(evt) {
  console.log(this.className);
  evt.preventDefault();
}

function delegate(
  evtType,
  context,
  target,
  callback,
  options
) {
  // As suggested by Paul, we only bind a single event
  // listener to a certain container element; the handler
  // callback will then get delegated to the event.target
  context.addEventListener(evtType, function(event) {

    // Check against arbitrary CSS selectors, such as
    // target = 'a.social'
    if (event.target.matches(target)) {

      // Instead of invoking the callback the usual way,
      // we explicitly set the execution context using 
      // `call()`.
      //
      // This way, `this` will refer to the actual target 
      // element within the callback function as expected.
      callback.call(event.target, event);
    }
  }, options);
}

var connect = document.querySelector('.connect');
delegate('click', connect, 'a', connectHandler, false);

PS: As for this or not to this, that’s something where JS really shines IMHO. You can dynamically set the execution context during runtime – the whole functionality gets more loosely coupled this way. So personally, I’d advocate to use this wherever it makes semantic sense.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.