Browse Source

debounce for v-model

Evan You 11 năm trước cách đây
mục cha
commit
2dee125bc1
2 tập tin đã thay đổi với 37 bổ sung0 xóa
  1. 5 0
      src/directives/model/default.js
  2. 32 0
      src/util/lang.js

+ 5 - 0
src/directives/model/default.js

@@ -12,6 +12,8 @@ module.exports = {
     var lazy = this._checkParam('lazy') != null
     // - number: cast value into number when updating model.
     var number = this._checkParam('number') != null
+    // - debounce: debounce the input listener
+    var debounce = parseInt(this._checkParam('debounce'), 10)
 
     // handle composition events.
     // http://blog.evanyou.me/2014/01/03/composition-event/
@@ -79,6 +81,9 @@ module.exports = {
           set()
         }
 
+    if (debounce) {
+      this.listener = _.debounce(this.listener, debounce)
+    }
     this.event = lazy ? 'change' : 'input'
     _.on(el, this.event, this.listener)
 

+ 32 - 0
src/util/lang.js

@@ -195,4 +195,36 @@ exports.define = function (obj, key, val, enumerable) {
     writable     : true,
     configurable : true
   })
+}
+
+/**
+ * Debounce a function so it only gets called after the
+ * input stops arriving after the given wait period.
+ *
+ * @param {Function} func
+ * @param {Number} wait
+ * @return {Function} - the debounced function
+ */
+
+exports.debounce = function(func, wait) {
+  var timeout, args, context, timestamp, result
+  var later = function() {
+    var last = Date.now() - timestamp
+    if (last < wait && last >= 0) {
+      timeout = setTimeout(later, wait - last)
+    } else {
+      timeout = null
+      result = func.apply(context, args)
+      if (!timeout) context = args = null
+    }
+  }
+  return function() {
+    context = this
+    args = arguments
+    timestamp = Date.now()
+    if (!timeout) {
+      timeout = setTimeout(later, wait)
+    }
+    return result
+  }
 }