3

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!

2 Answers 2

1

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/

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

1 Comment

There was one caveat--it's for use in a widget factory widget, and a response on the jQuery forum had the slightly altered code for a widgets internals:<code> toggle: function(){ var target; if ( $.isFunction(this.options.target) ) { target = this.options.target.call(this.element.get()); } else { target = $(this.options.target); } ... }</code>
0

pass the actual function, not the called function (i.e. drop the ()):

fn : $.fn.next

, toggle : function(){
    this.options.fn.apply( this.options.target, arguments );
}                                 ^
                                  |
    domNode ----------------------+

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.