摩纳哥编辑器AddComment事件触发两次

时间:2019-05-11 23:33:06

标签: javascript monaco-editor

我已将Monaco Editor配置为在Ctrl+S使用AddCommand时触发事件:

<html>
<head>
    <meta charset="utf-8" />
    <style type="text/css">
        body {
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>

    <div id="container" style="width:100%;height:700px;border:0px solid rgb(217, 219, 221);"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js"></script>
    <script src="{! URLFOR($Resource.monaco,'vs/loader.js')}"></script>

    <script>

        var editor;

        window.addEventListener("message", function (event) {

            let message = event.data;

            // stuff happens here that I've removed....

            let language = 'javascript';
            let code = 'no code found...';
            let readOnly = false;

            createEditor(code, language, readOnly);
        }, false);

        function createEditor(_code, _language, _readOnly) {

            var container = document.getElementById('container')
            while (container.firstChild) {
                container.removeChild(container.firstChild);
            }

            require.config({ paths: { "vs": "{! URLFOR($Resource.monaco,'vs')}" } });
            require(['vs/editor/editor.main'], function () {

                editor = monaco.editor.create(container, {
                    value: _code,
                    language: _language,
                    readOnly: _readOnly,
                });

                editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_S, function () {
                    let message = {};
                    message.action = 'save';
                    parent.postMessage(message, "*");
                    console.log('saved!!');
                })

                window.onresize = function () {
                    editor.layout();
                };
            });

        }

        createEditor('', 'apex');

    </script>
</body>

</html>

但是事件触发了两次。

以上代码在iframe中运行。

注意:如果仅按一个键,则事件不会执行,只有按两个键时,事件才会触发。

如何阻止事件触发两次?

0 个答案:

没有答案