0

I am new to require.js and I need little guidance here.

/*
 * 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. I probably could define init.js, but say I want to keep that idea behind, how do I define a function called init inside this main.js file and use it as my entry-point which calls functions in remote.js??

  2. Also, do I have to repeat define/require(['jquery', 'remote']..... the dependency array again when I define my function? Thanks

4

1 回答 1

1

你有很多选项可以做到这一点,但所有选择都需要你在 remote.js 中使用定义。

您可以使用名称-值对,但当您需要在 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();如果你选择第二种方法,你必须声明 using。

你需要设置 jquery 依赖,因为你不知道谁会使用你的 remote.js。

于 2013-09-06T02:24:59.430 回答