Reputation: 150
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!
Upvotes: 3
Views: 1308
Reputation: 126082
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/
Upvotes: 1
Reputation:
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 ----------------------+
Upvotes: 0