简体   繁体   English

为requirejs转换现有的javascript文件

[英]convert existing javascript file for requirejs

I had a javascript file like below.. First, I have some functions defined, and call the function on some event (document.ready here) 我有一个如下所示的javascript文件。首先,我定义了一些函数,并在某个事件上调用该函数(document.ready在此处)

function foo(arg) {
    return arg;
}

function bar(arg) {
    return arg;
}

$(document).ready(function(){
    doSomething();
});

Now I am trying to use requirejs and having trouble figuring out how to modify this file for it. 现在,我正在尝试使用requirejs,并且在弄清楚如何为其修改此文件时遇到了麻烦。

You can try this approach: 您可以尝试以下方法:

define(['dep'], function (dep) {  //If you have any dependency

    function foo(arg) {
      return arg;
    }

    function bar(arg) {
      return arg;
    }

    return {

      myMethods: {
        bar: bar(arg),
        foo: foo(arg)
      }

    };
});

You shouldn't include document.ready here. 您不应该在此处包含document.ready。 Instead use that where you are going to use this module as a dependency. 而是在要使用此模块作为依赖项的地方使用它。

This module will return myMethods object containing your methods. 此模块将返回包含您的方法的myMethods对象。

Let's say you would have two files, main.js, which contains the initial call to require, and code.js, which contains the code. 假设您有两个文件:main.js和code.js,其中main.js包含对require的初始调用,而code.js包含代码。 What you can do is this: 您可以执行以下操作:

in main.js 在main.js中

$(function () {

    require([
      "/Url_To_Code.JS_Here"
    ], function (
        code) {
          code.doSomething();
    });
});

in code.js: 在code.js中:

define(
    [],
    function () {   

        var foo = function () {

        }; 

        var doSomething = function () {

        };

        return {
            doSomething : doSomething 
        };
    }
);

so whatever you export from code.js (what is returned), you can access in main.js 因此,无论您从code.js导出(返回什么),都可以在main.js中进行访问

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM