Search code examples
jqueryjquery-uijquery-widgets

Call jQuery widgets dynamically at runtime


Lets imagine that I have some set of widgets: Widget1, Widget2 and Widget3.

How can I apply them according to some circumstances? Something like this:

if(case1)
    $('#container').Widget1()
else if(case2)
    $('#container').Widget2()
else if(case3)
    $('#container').Widget3()

if we have case only with three widgets IF-ELSE construction will probably perfectly works, but what if we have 10, 20 or even more?

I'm curious is there any way that would allow to call widgets by name? Is it possible to have function like this:

function ApplyWidget(name, options) {
    // apply widget here by 'name' with options
}

thanks in advance for any suggestions...


Solution

  • I think I found the answer...

    function ApplyWidget(name, options) {
        $('#container')[name](options);
    }
    

    here is working fiddle