Skip to content

Commit 2dee125

Browse files
committed
debounce for v-model
1 parent 6ec86ad commit 2dee125

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/directives/model/default.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ module.exports = {
1212
var lazy = this._checkParam('lazy') != null
1313
// - number: cast value into number when updating model.
1414
var number = this._checkParam('number') != null
15+
// - debounce: debounce the input listener
16+
var debounce = parseInt(this._checkParam('debounce'), 10)
1517

1618
// handle composition events.
1719
// http://blog.evanyou.me/2014/01/03/composition-event/
@@ -79,6 +81,9 @@ module.exports = {
7981
set()
8082
}
8183

84+
if (debounce) {
85+
this.listener = _.debounce(this.listener, debounce)
86+
}
8287
this.event = lazy ? 'change' : 'input'
8388
_.on(el, this.event, this.listener)
8489

src/util/lang.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,4 +195,36 @@ exports.define = function (obj, key, val, enumerable) {
195195
writable : true,
196196
configurable : true
197197
})
198+
}
199+
200+
/**
201+
* Debounce a function so it only gets called after the
202+
* input stops arriving after the given wait period.
203+
*
204+
* @param {Function} func
205+
* @param {Number} wait
206+
* @return {Function} - the debounced function
207+
*/
208+
209+
exports.debounce = function(func, wait) {
210+
var timeout, args, context, timestamp, result
211+
var later = function() {
212+
var last = Date.now() - timestamp
213+
if (last < wait && last >= 0) {
214+
timeout = setTimeout(later, wait - last)
215+
} else {
216+
timeout = null
217+
result = func.apply(context, args)
218+
if (!timeout) context = args = null
219+
}
220+
}
221+
return function() {
222+
context = this
223+
args = arguments
224+
timestamp = Date.now()
225+
if (!timeout) {
226+
timeout = setTimeout(later, wait)
227+
}
228+
return result
229+
}
198230
}

0 commit comments

Comments
 (0)