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]();
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
.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:
Then you could do:
obj.foo();– call a fixed name functionobj['foo']();– dynamic name fixed argumentsobj['foo'].apply(this, args)– dynamic function name and arguments.Edit:
One more thing I noticed:
In requirejs, when you do something like this:
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: