Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Widget, How can I pass a jQuery function in as a widget option

I'm creating a basic widget for toggling elements visibility. To initialize, the function looks like this:

$('button').collapsable({
    target:'#targetID'
});

I want to be able to pass a jquery function in, as example, this:

$('button').collapsable({
    target:$(this).next();
});

Simple example, the point is I'd like to be able to pass in more complex functions as needed. The trouble I'm having is how to call that within the widget to call that function on its self.

Such as (code not remotely correct)

toggle:function(){
    // i want it to firelike [this widget instances element].next();
    this.call[this.options.target]
}

But I have no idea how to write that to work. Any thoughts are appreciated. Thanks in advance!

like image 627
ted.goodridge Avatar asked Jan 18 '26 23:01

ted.goodridge


1 Answers

As @cwolves says, you need to pass a function reference. You could implement some logic to determine whether or not you're looking at a function or a selector, and act appropriately:

(function($) {
    $.fn.collapsible = function(options) {
        var self = this;
        var toggle = function () {
            /* options.target is a selector: */
            if (typeof options.target === "string") {
                $(options.target).toggle();
            } else if (typeof options.target === "function") {
                $(options.target.call(this)).toggle();
            }
        };

        this.click(toggle);
    };
})(jQuery);

Then you could use it like this:

$("#button").collapsible({
    target: "#foobar"
});

$("#button2").collapsible({
    target: function () {
        console.dir(this);
        return $(this).next();
    }
});

Example: http://jsfiddle.net/LVsys/

like image 78
Andrew Whitaker Avatar answered Jan 21 '26 13:01

Andrew Whitaker