0

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!

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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>' : '';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.