Skip to content

Commit

Permalink
Throttle and debounce
Browse files Browse the repository at this point in the history
  • Loading branch information
Akryum committed Jan 8, 2017
1 parent 5a25b15 commit 727db40
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "vue-apollo",
"version": "1.2.5",
"version": "1.3.0",
"description": "Vue apollo integration",
"main": "index.js",
"scripts": {
Expand Down Expand Up @@ -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",
Expand Down
10 changes: 9 additions & 1 deletion src/smart-apollo.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import omit from 'lodash.omit'
import { throttle, debounce } from './utils'

class SmartApollo {
type = null
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -125,6 +129,8 @@ export class SmartQuery extends SmartApollo {
'loadingKey',
'watchLoading',
'skip',
'throttle',
'debounce',
]

constructor (vm, key, options) {
Expand Down Expand Up @@ -245,6 +251,8 @@ export class SmartSubscription extends SmartApollo {
'variables',
'result',
'error',
'throttle',
'debounce',
]

constructor (vm, key, options) {
Expand Down
16 changes: 16 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
@@ -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)

0 comments on commit 727db40

Please sign in to comment.