vuejs / Discussion

Vue.js discussion
167 stars 17 forks source link

Request for debounced directive event listeners via `v-on` #245

Open GirlBossRush opened 9 years ago

GirlBossRush commented 9 years ago

I've created a generic debouncer for components that have potentially expensive event handlers.

/**
 * Dispatches a throttled event.
 * @param {String} name - Event name.
 * @returns {Function} throttledEvent - handler to be bound to a DOM element.
 */
function createDebouncedDispatcher (name) {
  if (!name) {
    return console.warn('expects an event name.');
  }

  var running = false;

  function throttledEvent () {
    if (running) {
      return;
    }

    running = true;

    global.requestAnimationFrame(function () {
      this.dispatchEvent(new global.CustomEvent(name));

      running = false;
    }.bind(this));
  }

  return throttledEvent;
}

var MyComponent = {
  beforeDestroy: function () {
    this.$el.removeEventListener('scroll', this.debouncedScrollHandler);
  },
  compiled: function () {
    this.debouncedScrollHandler = createDebouncedDispatcher('debouncedScroll');

    this.$el.addEventListener('scroll', this.debouncedScrollHandler, false);
  },
  methods: {
    handleDebouncedScroll: function () {
      console.log("Only executes one at time to prevent jittery scrolling.", this.$el.scrollTop);
    }
  }
};
<my-component v-on="debouncedScroll: handleDebouncedScroll"></<my-component>

It'd be awesome if components could debounce with a directive.

var MyComponent = {
  methods: {
    handleDebouncedScroll: function () {
      console.log("Only executes one at time to prevent jittery scrolling.", this.$el.scrollTop);
    }
  }
};
<my-component v-on="scroll: handleDebouncedScroll | debounce"></<my-component>

Do you have any thoughts on either approach?

Thank you!

yyx990803 commented 9 years ago

The debounce handler filter seems to be cleaner. The implementation could be similar to the internal key filter, you basically wrap the passed in handler and return a new handler.

GirlBossRush commented 9 years ago

The key filter was the inspiration for sure! While not totally unavoidable, it'd be great to consider manually added event listeners an antipattern.

Cheers.