So I think the best way for me to keep my code is to call a function with a dynamic 开发者_如何转开发name. For example, I might need to call "productTemplate", "userTemplate", "orderTemplate", etc...
Is this possible with javascript/jquery? Also, is it a performance hit or not so much?
It's possible in basic JavaScript, no jQuery needed, whatever the object is, even window
you can use bracket notation, for example:
var methodName = "productTemplate";
obj[methodName](); //exe obj.productTemplate();
The same holds true for global functions, just replace obj
with window
. You can do this with your jQuery plugins or core as well though, for example here's how .toggle(bool)
works, actually using .show()
and .hide()
internally:
$("selector")[bool ? "show" : "hide"]()
How about storing those functions under an object? You could probably call those function names dynamically by using eval
or accessing them with window[type + 'Template']
, but the object implementation seems easier and cleaner.
var templates = {};
templates.order = function (order) { /* ... */ }
templates.product = function (product) { /* ... */ }
templates.user = function (user) { /* ... */ }
my_element.innerHTML = templates.user(my_user);
(Also, the jQuery Templates plugin created by Microsoft might help with what you're particularly trying to do. It's so good that it's gonna be built right into jQuery 1.5, dontchaknow.)
精彩评论