requireJS - sustitución de parámetros

How should I get this to work ?

var param = 'someFunction';

require('views/MyView').[param]();

When I run this code, I get the following error

SyntaxError: missing name after . operator
require('views/MyView').[renderMethod]();

preguntado el 28 de agosto de 12 a las 14:08

1 Respuestas

. y [] are kind of the same thing.

Lo que quieres es require('views/MyView')[renderMethod]();

require(...) will return the exported module, which should basically be an object with the functions as properties.

So, let's say we have:

var obj = {
   foo: function() { alert('foo'); }
   bar: function() { alert('bar'); }
}

Entonces podrías hacer:

obj.foo(); - call a fixed name function

obj['foo'](); - dynamic name fixed arguments

obj['foo'].apply(this, args) - dynamic function name and arguments.

Edit:

Una cosa más que noté:

In requirejs, when you do something like this:

define (require, function() {
    x = require('views/Foo');
    x.bar();
}

RequireJS will determine by parsing the code that you will need the 'view/Foo' module, and make sure it is loaded before executing your code.

But if you want to load a dynamic module, it won't know beforehand what module to preload, so you will have to use a callback to be notified when your module will be loaded:

define (require, function() {

    require('views/' + viewName, function(myView) {
        myView.bar(); // or 
        myView[dynamicFunc](); // ... 
    });
}

Respondido 28 ago 12, 14:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.