Domanda

ho iniziato a leggere diversi tutorial su RequireJS. In nessuno di loro è stata la parola chiave "definire", ha spiegato in modo soddisfacente per me. Potrebbe qualcuno aiutarlo con la seguente:

define(
  ["Models/Person", "Utils/random", "jquery"], 
  function (Person, randomUtility, $) {..}
)  

Che cosa è "definire"? È definire una funzione con una matrice e una funzione interna anonima di esso? O è qualcos'altro? Qualcuno può darmi maggiori informazioni su questo tipo di definizioni?

Aggiunta: Grazie nnnnnn e pradeek per le vostre risposte. Qui in Europa è stato 2:30 la notte in cui mi è stato la pubblicazione della domanda. Forse quindi non ho riconosciuto che era una semplice chiamata di funzione.

È stato utile?

Soluzione

define non è specifico per RequireJS, è parte del AMD specifica . Burke noterà che RequireJS non implementa esattamente come AMD specifica, dal momento che AMD non ha davvero tenere a mente i browser.

define non ha una funzione anonima in esso. define è un metodo messo a disposizione i file JavaScript basati AMD per caricare i loro dati. Librerie come RequireJS rendono questo a vostra disposizione. L'implementazione specifica probabilmente non è prezioso per voi. Così vado su quello che hai fornito in quanto è il modo più comune per dichiarare un modulo.

define( [array], object );

Array è una lista dei moduli che questo modulo dipende. V'è una relazione 1 a 1 tra i moduli e file. Non si può avere più moduli in un file, né più file per un modulo.

Oggetto è il modulo che si sta definendo. Questo può essere qualsiasi cosa, una struttura o una funzione che restituisce una struct. Leggi la documentazione su RequireJS per ulteriori dettagli.

Se oggetto è una funzione, gli argomenti passati alla funzione sono i moduli elencati come dipendenze nell'argomento prima definire. E 'anche importante notare che quando si passa una funzione come object, viene attivata una sola volta. I metodi o proprietà creati su questo istanza può accedere in qualsiasi momento però, possono poi essere accessibili da altri moduli che elenco questo modulo come dipendenza.

Buona fortuna, vi consiglio di giocare con questo e leggendo i documenti quando le cose non hanno senso. RequireJS documenti sono grandi come un avvio rapido su come AMD moduli di lavoro.

Altri suggerimenti

Ho trovato define definito nella parte inferiore della require.js (anche io chiedevo che tipo di cosa questa parola define è, e questa è la risposta I era alla ricerca di):

/**
 * The function that handles definitions of modules. Differs from
 * require() in that a string for the module should be the first argument,
 * and the function to execute after dependencies are loaded should
 * return a value to define the module corresponding to the first argument's
 * name.
 */
define = function (name, deps, callback) {
    var node, context;

    //Allow for anonymous modules
    if (typeof name !== 'string') {
        //Adjust args appropriately
        callback = deps;
        deps = name;
        name = null;
    }

    //This module may not have dependencies
    if (!isArray(deps)) {
        callback = deps;
        deps = null;
    }

    //If no name, and callback is a function, then figure out if it a
    //CommonJS thing with dependencies.
    if (!deps && isFunction(callback)) {
        deps = [];
        //Remove comments from the callback string,
        //look for require calls, and pull them into the dependencies,
        //but only if there are function args.
        if (callback.length) {
            callback
                .toString()
                .replace(commentRegExp, '')
                .replace(cjsRequireRegExp, function (match, dep) {
                    deps.push(dep);
                });

            //May be a CommonJS thing even without require calls, but still
            //could use exports, and module. Avoid doing exports and module
            //work though if it just needs require.
            //REQUIRES the function to expect the CommonJS variables in the
            //order listed below.
            deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
        }
    }

    //If in IE 6-8 and hit an anonymous define() call, do the interactive
    //work.
    if (useInteractive) {
        node = currentlyAddingScript || getInteractiveScript();
        if (node) {
            if (!name) {
                name = node.getAttribute('data-requiremodule');
            }
            context = contexts[node.getAttribute('data-requirecontext')];
        }
    }

    //Always save off evaluating the def call until the script onload handler.
    //This allows multiple modules to be in a file without prematurely
    //tracing dependencies, and allows for anonymous module support,
    //where the module name is not known until the script onload event
    //occurs. If no context, use the global queue, and get it processed
    //in the onscript load callback.
    (context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
};

Ho trovato questo sito Perché AMD? molto utile. Per riassumere da questa pagina, specifica AMD è utile a superare "scrivere un mucchio di tag script con dipendenze implicite che dovete ordinare manualmente" problema. E 'utile per caricare le dipendenze prima di eseguire le funzioni richieste, simili a import in altri linguaggi di programmazione come Python. AMD impedisce anche il problema dell'inquinamento globale dello spazio dei nomi. Controllare la sezione "It is an improvement over the web's current "globals and script tags" because".

Credo che le RequireJs API specifica riassume abbastanza bene:

Se il modulo presenta dipendenze, il primo argomento dovrebbe essere un array di nomi di dipendenza, e il secondo argomento dovrebbe essere una funzione definizione. La funzione verrà chiamata per definire il modulo dopo tutte le dipendenze sono caricati. La funzione dovrebbe restituire un oggetto che definisce il modulo.

Si elencano esempi di tutte le varie forme sintattiche definisce.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top