Reputation: 750
Not sure if I'm approaching this correctly ...
Basically I have a plugin structure along the lines of:
(function($){
$.fn.xxxxx = function(options) {
var o = {
widgets: 'a,b,c',
a: {
id: 'abc',
title: 'ABC'
},
b: {
id: 'def',
title: 'DEF'
},
c: {
id: 'ghi',
title: 'GHI'
}
};
var options = $.extend(o, options);
return this.each(function(options){
var myplugin = {
init: function(){
var x = o.widgets.split(',');
$.each(x, function(i,v){
myplugin.widgets(i,v);
});
},
widgets: function(i,v){
var t = o.v.title ? '<h3>'+o.v.title+'</h3>' : '' ;
}
}
myplugin.init();
});
};
})(jQuery);
Is it possible to use the string values from the o.widgets option to then call one of the o.a, o.b, o.c options?
Basically the a, b or c would be passed to the widgets function and then used to assign the option value. The following is what I want it to do but it obviously doesnt work like that:
var t = o.v.title ? '<h3>'+o.v.title+'</h3>' : '' ;
Any help appreciated!
Upvotes: 0
Views: 52
Reputation: 272066
You can do this:
var t = o['a'].title ? '<h3>' + o['a'].title + '</h3>' : '';
Which allows you to do this:
var v = 'a';
var t = o[v].title ? '<h3>' + o[v].title + '</h3>' : '';
Upvotes: 1
Reputation: 14747
Well, one of the nice things about Javascript in particular is that the following are equivalent:
foo.bar === foo['bar'];
So if you want to access o.a
, you can access it via o['a']
.
Taking that further, you can fashion a function like the following:
function herp (opt) {
return o[opt];
}
... and call it like var foo = herp('a');
or something.
Upvotes: 1