VueJS Custom Directive to Capture Multiple Events

Vue JS Custom Directive to Capture Multiple Events

by Jayesh Vachhani

HTML

<script src="https://vuejs.org/js/vue.min.js"></script>
<div id="vue">
  <h1>
  VueJS Custom Directive to Capture Multiple Events 
  </h1>
  <span style="padding: 40px"> FIRST </span>
  <input v-multi-event="{ evt: ['click', 'blur', 'change', 'keydown'], fn: firstMethod }">
  <br/>
  <br/>
  <span style="padding: 30px"> SECOND</span>
  <input v-multi-event="{ evt: ['click', 'keydown'], fn: secondMethod }">
  <p>
    FIRST's Event: <b>{{first}}</b>
  </p>
  <p>
    SECONDS's Event: <b>{{second}}</b>
  </p>
  <em> Please view the console logs for more details.</em>
</div>

JavaScript

function functionWrapper(e) {
  /* add filters to handle event type before propagating to callback function for custom event handler */
  e.target.__handler__.fn(e)
}
Vue.directive('multiEvent', {
  bind: function(el, binding, vnode) {
    console.log('bind')
    el.__handler__ = binding.value
    binding.value.evt.forEach(e => el.addEventListener(e, functionWrapper))
  },
  unbind: function(el, binding) {
    console.log('unbind')
    el.__handler__.evt.forEach(e => el.removeEventListener(e, functionWrapper))
    el.__handler__ = null
  }
})
new Vue({
  el: '#vue',
  data: {
    first: '',
    second: ''
  },
  methods: {
    firstMethod(e) {
        console.log('First Method')
        console.log(e)
        this.first = e.type
      },
      secondMethod(e) {
        console.log('Second Method')
        console.log(e)
        this.second = e.type
      }
  }
})