From 727db404bf6b03c26dcd8515a2d44c71cd4b9b05 Mon Sep 17 00:00:00 2001 From: Guillaume Chau Date: Sun, 8 Jan 2017 03:12:48 +0100 Subject: [PATCH] Throttle and debounce --- package.json | 6 ++++-- src/smart-apollo.js | 10 +++++++++- src/utils.js | 16 ++++++++++++++++ 3 files changed, 29 insertions(+), 3 deletions(-) create mode 100644 src/utils.js diff --git a/package.json b/package.json index ba869cd..56aca9e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "vue-apollo", - "version": "1.2.5", + "version": "1.3.0", "description": "Vue apollo integration", "main": "index.js", "scripts": { @@ -31,7 +31,9 @@ }, "dependencies": { "graphql-tag": "^0.1.15", - "lodash.omit": "^4.5.0" + "lodash.debounce": "^4.0.8", + "lodash.omit": "^4.5.0", + "lodash.throttle": "^4.1.1" }, "devDependencies": { "babel-cli": "^6.14.0", diff --git a/src/smart-apollo.js b/src/smart-apollo.js index 6ce2aaa..c7c4627 100644 --- a/src/smart-apollo.js +++ b/src/smart-apollo.js @@ -1,4 +1,5 @@ import omit from 'lodash.omit' +import { throttle, debounce } from './utils' class SmartApollo { type = null @@ -62,7 +63,10 @@ class SmartApollo { start () { this.starting = true if (typeof this.options.variables === 'function') { - this.unwatchVariables = this.vm.$watch(this.options.variables.bind(this.vm), this.executeApollo.bind(this), { + let cb = this.executeApollo.bind(this) + cb = this.options.throttle ? throttle(cb, this.options.throttle) : cb + cb = this.options.debounce ? debounce(cb, this.options.debounce) : cb + this.unwatchVariables = this.vm.$watch(this.options.variables.bind(this.vm), cb, { immediate: true, }) } else { @@ -125,6 +129,8 @@ export class SmartQuery extends SmartApollo { 'loadingKey', 'watchLoading', 'skip', + 'throttle', + 'debounce', ] constructor (vm, key, options) { @@ -245,6 +251,8 @@ export class SmartSubscription extends SmartApollo { 'variables', 'result', 'error', + 'throttle', + 'debounce', ] constructor (vm, key, options) { diff --git a/src/utils.js b/src/utils.js new file mode 100644 index 0000000..3963f65 --- /dev/null +++ b/src/utils.js @@ -0,0 +1,16 @@ +import loThrottle from 'lodash.throttle' +import loDebounce from 'lodash.debounce' + +function factory (action) { + return (cb, options) => { + if (typeof options === 'number') { + return action(cb, options) + } else { + return action(cb, options.wait, options) + } + } +} + +export const throttle = factory(loThrottle) + +export const debounce = factory(loDebounce)