javascriptx-tag

x-tag event delegation: accessing the root element


I need to delegate a 'tap' event to a close button in a custom element, and in turn call a close() method on the root element. Here is an example:

xtag.register('settings-pane', {
  lifecycle: {
    created: function () {
      var tpl = document.getElementById('settings-pane'),
          clone = document.importNode(tpl.content, true);
      
      this.appendChild(clone);
    }
  },
  events: {
    'tap:delegate(button.close)': function (e) {
      rootElement.close(); // <- I don't know the best way to get rootElement
    }
  },
  methods: {
    close: function () {
      this.classList.add('hidden');
    }
  }
});
<template id="settings-pane">
  <button class="close">✖</button>
</template>


Solution

  • ​Hey there, this is the library author, let me clear this up:

    For any listener you set in the DOM, X-Tag or vanilla JS, you can always use the standard property e.currentTarget to access the node the listener was attached to. For X-Tag, whether you're using the delegate pseudo or not, e.currentTarget will always refer to your custom element:

    xtag.register('x-foo', {
      content: '<input /><span></span>',
      events: {
        focus: function(e){
          // e.currentTarget === your x-foo element
        },
        'tap:delegate(span)': function(e){
          // e.currentTarget still === your x-foo element
          // 'this' reference set to matched span element
        }
      }
    });
    

    Remember, this is a standard API for accessing the element an event listener was attached to, more here: https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget