Skip to content

Instantly share code, notes, and snippets.

@MarkBorcherding
Created May 1, 2010 19:04
Show Gist options
  • Save MarkBorcherding/386578 to your computer and use it in GitHub Desktop.
Save MarkBorcherding/386578 to your computer and use it in GitHub Desktop.
$('#foo1').foo();
$('#foo2').foo({bar:'baz'});
// later on, maybe in a event handler of something else.
// These calls need the options set up above, but the way they are defined,
// they are not in the closure of $.fn.foo function block
$('#foo1').foo('doFoo');
$('#foo2').foo('doFoo');
(function($){
$.fn.foo = function(options){
// Handle API methods
if(typeof arguments[0]=='string'){
// Perform API methods on individual elements
if(this.length>1){
var args = arguments;
return this.each(function(){
$.fn.foo.apply($(this), args);
});
};
// Invoke API method handler
$.fn.foo[arguments[0]].apply(this, $.makeArray(arguments).slice(1) || []);
return this;
}
var options = $.extend($.fn.foo.options, options);
// Is this OK?
// stash the options on the items so we can use them in the API
$(this).data('foo-options',options);
console.debug('options.bar = ',options.bar);
};
$.extend($.fn.foo, { doFoo: function(){
console.debug('in doFoo bar = ', $(this).data('foo-options').bar);
}
});
$.fn.foo.options = { bar:'bar'};
})(jQuery);
@MarkBorcherding
Copy link
Author

I need to use the options in the API extensions, but not sure the best way to pass them down there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment