简体   繁体   中英

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)

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.

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. Instead use that where you are going to use this module as a dependency.

This module will return myMethods object containing your methods.

Let's say you would have two files, main.js, which contains the initial call to require, and code.js, which contains the code. What you can do is this:

in main.js

$(function () {

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

in 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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