Debouncing CodeMirror Input on change event

≯℡__Kan透↙ 提交于 2020-06-17 14:19:31

问题


I have a very simple implementation of EasyMDE, which internally uses CodeMirror. So to check for change of input I need to do this as said in the EasyMDE docs. Which works fine and I can even detect for change and get the input value as well.

The problem right now I facing is that, there is no debounce available in both EasyMDE/CodeMirror and I am syncing the input on change to my backend functionality. On every input event I cant afford to sync to backend as it is may become very expensive.

This is the code without debounce

    new EasyMDE({
        element: $refs.input,
        toolbar: ['bold', 'italic', 'heading', '|', 'quote', 'unordered-list', 'ordered-list', 'clean-block', '|', 'link', 'image', 'table', 'horizontal-rule' ,'|', 'preview'],
        previewClass: ['markdown', 'editor-preview'],
        renderingConfig: {
            codeSyntaxHighlighting: true,
            hljs: window.hljs
        }
    })
    .codemirror.on('change', function(event, changeObj) {  
        //backend sync code comes here
    });

I tried to add debounce function and but it does not work, meaning the debounce is calling the function when the change happens.

    function inputDebounce(func, wait, immediate) {
        var timeout;

        return function executedFunction() {
            var context = this;
            var args = arguments;

            var later = function() {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };

            var callNow = immediate && !timeout;

            clearTimeout(timeout);

            timeout = setTimeout(later, wait);

            if (callNow) func.apply(context, args);
        };
    };

    new EasyMDE({
        element: $refs.input,
        toolbar: ['bold', 'italic', 'heading', '|', 'quote', 'unordered-list', 'ordered-list', 'clean-block', '|', 'link', 'image', 'table', 'horizontal-rule' ,'|', 'preview'],
        previewClass: ['markdown', 'editor-preview'],
        renderingConfig: {
            codeSyntaxHighlighting: true,
            hljs: window.hljs
        }
    })
    .codemirror.on('change', function(event, changeObj) {  
        inputDebounce(function() { console.log('asdfasdf asdf asdf asdf asdf ') }, 2000);
    });

Debounce function referenced from : Debounce Article

来源:https://stackoverflow.com/questions/62157612/debouncing-codemirror-input-on-change-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!