0

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]();

1 Answer 1

3

. and [] are kind of the same thing.

What you want is 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'); }
}

Then you could do:

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

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

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

Edit:

One more thing I noticed:

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](); // ... 
    });
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.