opti: throttle util

This commit is contained in:
Jocs 2017-11-19 22:09:30 +08:00
parent bdf88882c1
commit e253ff5313
4 changed files with 37 additions and 20 deletions

View File

@ -47,16 +47,4 @@ export const CLASS_OR_ID = genUpper2LowerKeyHash([
'AG_EMOJI_MARKED_TEXT'
])
export const paragraphClassName = 'aganippe-paragraph'
export const activeClassName = 'aganippe-active'
export const EDITOR_ATTR_NAME = 'aganippe-editor-element'
export const EDITOR_ID = 'write'
export const FLOAT_BOX_ID = 'ag-float-emoji-box'
export const FLOAT_BOX_CLASSNAME = 'ag-float-emoji-box'
export const SHOW_EMOJI_BOX = 'ag-float-emoji-box-show'
export const EMOJI_ITEM = 'ag-emoji-item'
export const EMOJI_ITEM_ACTIVE = 'ag-emoji-active'
export const EMOJI_ICON = 'ag-emoji-item-icon'
export const EMOJI_MARKED_TEXT = 'ag-emoji-marked-text'
// export const markedSymbol = ['*', '-', '_', '!', '[', ']']

View File

@ -46,7 +46,7 @@ class Aganippe {
eventCenter.subscribe('markedTextChange', this.subscribeMarkedText.bind(this))
this.dispatchMarkedText()
eventCenter.subscribe('editEmoji', throttle(this.subscribeEditEmoji.bind(this)))
eventCenter.subscribe('editEmoji', throttle(this.subscribeEditEmoji.bind(this), 200))
this.dispatchEditeEmoji()
eventCenter.subscribe('enter', this.subscribeEnter.bind(this))

0
src/editor/records.js Normal file
View File

View File

@ -19,13 +19,42 @@ export const getUniqueId = set => {
return id
}
export const throttle = fn => {
let timer = null
return (...args) => {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fn(...args)
}, 300)
// https://github.com/jashkenas/underscore
export const throttle = (func, wait = 50) => {
let context
let args
let result
let timeout = null
let previous = 0
const later = () => {
previous = Date.now()
timeout = null
result = func.apply(context, args)
if (!timeout) {
context = args = null
}
}
return function () {
const now = Date.now()
const remaining = wait - (now - previous)
context = this
args = arguments
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout)
timeout = null
}
previous = now
result = func.apply(context, args)
if (!timeout) {
context = args = null
}
} else if (!timeout) {
timeout = setTimeout(later, remaining)
}
return result
}
}
/**