繁体   English   中英

如何在require.js中定义一个函数并加载它?

[英]How do you define a function in require.js and load it?

我是require.js的新手,这里不需要任何指导。

/*
 * This app depends on jquery and a remote script called "remote.js" (serve over localhost :p)
 * Locally I will have main.js and require.js.
 * main.js contain an entry function "init" and it depends on jquery
 * and remote.js to be fully loaded.
 */
require.config({
    paths: {
        "jquery": "https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min",
        "remote": "http://localhost:8000/scripts/remote"
    },  
    shim: {
        "init": {
            deps: ["jquery", "remote"]
        }  
    },  
    urlArgs: "bust=" + (new Date()).getTime()
});

define(["jquery", "remote"], function($, remote) {
    console.log("just entered the outerscope of the init function.");
    console.log(remote);
    return {
        init: function() {
            console.log("entered init function");
        }  
    }  
});

/* the following is in remote.js*/
function remoteF1() {
    console.log("remote function 1 is called.");
};

function remoteF2() {
    console.log("remote function 2 is called.");
};
// and I thought about wrapping them around with "define" or "require"
  1. 我可能可以定义init.js,但是我想保留这个想法,如何在main.js文件中定义一个名为init的函数,并将其用作在remote.js中调用函数的入口点?

  2. 另外,我在定义函数时是否必须重复define/require(['jquery', 'remote'].....依赖项数组?

您有很多选择来执行此操作,但是所有选择都需要您在remote.js内部使用define。

您可以使用名称-值对,并且在需要在remoteF1中使用remoteF2时遇到一些问题:

define(["jquery"], function($) {
    return {
        remoteF1: function() {
            console.log("remoteF1 is called.");
        },
        remoteF2: function() {
            console.log("remoteF2 is called.");
        }
    }   
});

现在您可以在main.js中执行此操作:

define(["jquery", "remote"], function($, remote) {
    console.log("just entered the outerscope of the init function.");
    console.log(remote);
    var remote = new remote();
    remote.remoteF1();
});

或者您可以返回一个js对象:

define(["jquery"],function($){
    return function(){
        var privateFunction = function(){};
        this.remoteF1 = function () {
            privateFunction();
            console.log("remote function 1 is called.");
        };     
        this.remoteF2 = function () {
            console.log("remote function 2 is called.");
        };
    }
});

使用remote.js时,必须声明使用new remote(); ;。 您应该选择第二种方法。

您需要设置jquery依赖关系,因为您不知道谁将使用remote.js。

暂无
暂无

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

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