2017-06-26 61 views
1

我創建了一個反跳效用函數:爲什麼這個去抖功能打破「這個」?

debounce (func, wait, immediate) { 
    let timeout 
    return function() { 
    const context = this 
    const args = arguments 
    const later = function() { 
     timeout = null 
     if (!immediate) func.apply(context, args) 
    } 
    const callNow = immediate && !timeout 
    clearTimeout(timeout) 
    timeout = setTimeout(later, wait) 
    if (callNow) func.apply(context, args) 
    } 
} 

,我用這樣的:

updateField: utils.debounce((event, fieldName, schema) => { 
    const value = event.target.value 
    this.$emit('updateField', fieldName, value, schema) 
    validateFields(this) 
}, 500), 

去抖動功能工作。但是我得到這個錯誤:

Uncaught TypeError: _this.$emit is not a function 

有什麼問題?

回答

1

假設updateField是Vue方法,因爲它用Vue標記,這是因爲您正在使用箭頭函數。

將其更改爲常規功能。

updateField: utils.debounce(function(event, fieldName, schema){ 
    const value = event.target.value 
    this.$emit('updateField', fieldName, value, schema) 
    validateFields(this) 
}, 500) 

您不應該使用箭頭函數定義Vue方法。原因是Vue將方法綁定到Vue,並且箭頭函數不能被綁定(您不能更改它們的this)。