RequireJS and functions

RequireJS and functions

本文关键字:functions and RequireJS      更新时间:2023-09-26

我的main.js有一部分包含如下功能:

function isTrue(x){...}
function resizeEditors() {...}
function updateLayout() {...}
function prettify() {...}
function setTheme(theme) {...}
function themedLayout(isDark){...}
function enablePanel(panel) {...}
function disablePanel(panel) {...}
function enableDefaultPanels() {...}
function toggleFullscreen() {...}
function toggleEditorFullscreen(selected) {...}

是否有办法使这些功能可用于我的main.js文件的依赖关系?

例如,在editors.js中,我使用isTrue函数,但editors.js模块目前无法找到isTrue,因为它位于main.js文件

editors.setShowPrintMargin( isTrue( settings.showPrintMargin ) );

编辑:

项目的样子:

main.js:

require(['jquery', 'appSession', 'editors'], function ($, appSession, editors) {
    function isTrue(x){...}
    function resizeEditors() {...}
    function updateLayout() {...}
    function prettify() {...}
    function setTheme(theme) {...}
    function themedLayout(isDark){...}
    function enablePanel(panel) {...}
    function disablePanel(panel) {...}
    function enableDefaultPanels() {...}
    function toggleFullscreen() {...}
    function toggleEditorFullscreen(selected) {...}
});

editors.js:

define(['jquery', 'appSession'], function($, appSession){
    ...
    editors.setShowPrintMargin( isTrue( settings.showPrintMargin ) );
    ...
    return editors;
});

可以,可以返回。

define(function () {
    return {
        isTrue: function() {
            // Code
        },
        otherFunction: function() {
            // Code
        }
    }
});

然后使用

require(["main"], function(main) {
    main.isTrue(false);
});

你可以创建一个包含共享/全局功能的模块,并使其成为需要它的模块的依赖项:

globals.js:

define([], function() {
    function isTrue(x){}
    // rest of functions...
    function toggleEditorFullscreen(selected) {}
    return { // return functions... };
});

然后使用:

require(["globals", "editors"], function(globals, editors) {
    // ...
    editors.setShowPrintMargin(globals.isTrue(settings.showPrintMargin));
    // ...
});

或者如果你想在编辑器模块中使用它,你的editor .js看起来像:

define(["globals"], function(globals) {
    // ...
    setShowPrintMargin(globals.isTrue(settings.showPrintMargin));
    // ...
});

或者,如果你真的希望它们是全局的,你应该可以这样做:

window.isTrue = function(valueToCheck) {
    // implementation ...
};