Let us say there are some widgets:
function Widget1(initData) {
....
}
Widget1.prototype.render = function() {
....
}
function Widget2(initData) {
....
}
Widget2.prototype.render = function() {
....
}
What I need to do is the following:
$.subscribe('/launch', function(widgetName, initData) {
// create a new object of the widget and then call the render method
});
I dont want to write multiple if-else blocks as the number of widgets may become very large. One option is to use eval(), but I believe that there may be better techniques. I am using JQuery framework, so don’t want to include any other frameworks that may have a specific feature to support this. A pure Javascript solution will be appreciated.
Yep, there is a way. When you create a function, it’s created as a property of the
thisobject in that context. So if you declare those Widget functions in the global scope, they become properties of thewindowobject. As you probably know, you can access a property both asobject.propertyorobject['property']. So, if they are global, you can do something like:EDIT: As T.J. Crowder said, I was horribly wrong. What I said about the function being created as a property of
thisapplies when you’re on the global scope (I want to say “only when you’re on the global scope”, but since I’m not 100% sure I’m gonna leave it as that).